Skip to content

Instantly share code, notes, and snippets.

@robertdfrench
Created April 4, 2025 18:29
Show Gist options
  • Save robertdfrench/6c689f90e8dd846c968ba68a1fd02578 to your computer and use it in GitHub Desktop.
Save robertdfrench/6c689f90e8dd846c968ba68a1fd02578 to your computer and use it in GitHub Desktop.
Compute the Fibonacci Sequence with m4 macros
# Fibonacci Macros
# ================
define(`FIB', `ifelse(`$3',`2',`$2',`FIB($2,expr($1 + $2),decr($3))')')dnl
* 12th Fibonacci Number: FIB(0,1,12)
# Use brackets for quotes instead of ` and '
changequote([,])dnl
# Decrement a literal number
decr(3)
# Define a variable X and then decrement it
define([X], [3])dnl
decr(X)
# expr() lets you do simple arithmetic
expr(3 - 1)
expr(X - 1)
define([DOUBLE], [expr($1 * 2)])dnl
DOUBLE(5)
define([SQUARE], [expr($1 * $1)])dnl
SQUARE(X)
define([ADD], [expr($1 + $2)])dnl
ADD(2, X)
# ifelse works like this:
# * if the first and second arguments match, it returns the third argument
# * if they don't match, it returns the fourth argument
ifelse([a],[a],[they match!],[they don't match...])
ifelse([a],[b],[they match!],[they don't match...])
# You can use ifelse to provide a 'stop case' to prevent infinite recursion.
define([T_MINUS], [ifelse([$1],[0],[blastoff!],[$1 T_MINUS(decr($1))])])dnl
Ignition: T_MINUS(5)
# Nicer Fibonacci
define([FIB], [ifelse([$3],[2],[$2],[FIB($2,expr($1 + $2),decr($3))])])dnl
0
FIB([0],[1],[2])
FIB([0],[1],[3])
FIB([0],[1],[4])
FIB([0],[1],[5])
FIB([0],[1],[6])
FIB([0],[1],[7])
FIB([0],[1],[8])
FIB([0],[1],[9])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment