Skip to content

Instantly share code, notes, and snippets.

@mwgamera
Created April 15, 2014 10:56
Show Gist options
  • Save mwgamera/10722748 to your computer and use it in GitHub Desktop.
Save mwgamera/10722748 to your computer and use it in GitHub Desktop.
dnl The Game of Life in POSIX macro processor M4
dnl klg, Apr 2014
dnl
divert(-1)
define(`local',`pushdef(`$1',`$2')`'$3`'popdef(`$1')')
define(`silent',
`local(`__divnum',divnum,`divert(-1)$*`'divert(__divnum)')')
define(`for',`ifelse(eval(`$2'<`$3'),`1',dnl
`local(`$1',`$2',`$4')`'$0(`$1',incr(`$2'),`$3',`$4')')')
define(`while',
`ifelse(eval($1),`0',,`$2`'$0(`$1',`$2')')')
define(`mod',`eval((`$2'+`$1'%`$2')%`$2')')
define(`idx',``__'translit(`$*',`,',`_')')
define(`mem',`idx(mod(`$1',W),mod(`$2',H),$3)')
define(`set',`define(mem(shift($*)),`$1')')
define(`get',`ifdef(mem($*),mem($*),`0')')
define(`foryx',`for(`y',0,H,`for(`x',0,W,`$1')$2')')
define(`life',`silent(`
foryx(`set(0,`x',`y',`tmp')')
foryx(`
ifelse(get(`x',`y'),`1',`
for(`j',-1,2,`for(`i',-1,2,`
set(eval(get(`x+i',`y+j',`tmp')+1),`x+i',`y+j',`tmp')
')')
')
')
define(`changed', 0)
foryx(`
local(`count',`get(`x',`y',`tmp')',`
local(`old', `get(`x',`y')',`
local(`new', `eval(count==3 ||(old && count==4))', `
define(`changed', eval((old != new) + changed))
set(new,`x',`y')
')')')
')
')')
define(`showboard',
`foryx(`local(`c',`get(`x',`y',`$1')',`ifelse(c,`1',`@',`.')')',`
')')
define(`patset',`silent(`
for(`i',0,len(`$3'),`
ifelse(substr(`$3',i,1),`@',`set(1,`$1+i',`$2')')
')
ifelse(`$4',,,
`patset(`$1',`$2+1',shift(shift(shift($*))))')
')')
divert`'dnl
dnl
define(`W', `35')dnl
define(`H', `15')dnl
dnl
patset(
15, 6,
`.@@',
`@@.',
`.@.'
)dnl
dnl
define(`changed', 1)dnl
define(`generation', 0)dnl
while(`changed && generation < 1000', `
generation:define(`generation',incr(generation))
showboard`'life')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment