Home | History | Annotate | Line # | Download | only in unit-tests
      1  1.5  rillig # $NetBSD: hanoi-include.mk,v 1.5 2023/10/19 18:24:33 rillig Exp $
      2  1.1  rillig #
      3  1.3  rillig # Implements the Towers of Hanoi puzzle, demonstrating a bunch of more or less
      4  1.3  rillig # useful programming techniques:
      5  1.1  rillig #
      6  1.3  rillig #	* default assignment using the ?= assignment operator
      7  1.3  rillig #	* including the same file recursively (rather unusual)
      8  1.3  rillig #	* extracting the current value of a variable using the .for loop
      9  1.3  rillig #	* using the :: dependency operator for adding commands to a target
     10  1.3  rillig #	* on-the-fly variable assignment expressions using the ::= modifier
     11  1.1  rillig #
     12  1.1  rillig # usage:
     13  1.3  rillig #	env N=3 make -r -f hanoi-include.mk
     14  1.3  rillig #
     15  1.5  rillig # Specifying N in the command line instead of in the environment would produce
     16  1.5  rillig # an endless loop, since variables from the command line cannot be overridden
     17  1.5  rillig # by global variables:
     18  1.3  rillig #	make -r -f hanoi-include.mk N=3
     19  1.1  rillig 
     20  1.1  rillig N?=	5			# Move this number of disks ...
     21  1.1  rillig FROM?=	A			# ... from this stack ...
     22  1.1  rillig VIA?=	B			# ... via this stack ...
     23  1.1  rillig TO?=	C			# ... to this stack.
     24  1.1  rillig 
     25  1.4  rillig # Since make has no built-in arithmetic functions, convert N to a list of
     26  1.4  rillig # words and use the built-in word counting instead.
     27  1.4  rillig .if ${N:[#]} == 1
     28  1.4  rillig N:=	count ${:U:${:Urange=$N}}	# 'count' + one word for every disk
     29  1.4  rillig .endif
     30  1.4  rillig 
     31  1.4  rillig .if ${N:[#]} == 2
     32  1.1  rillig .  for from to in ${FROM} ${TO}
     33  1.1  rillig all::
     34  1.1  rillig 	@echo "Move the upper disk from stack ${from} to stack ${to}."
     35  1.1  rillig .  endfor
     36  1.1  rillig .else
     37  1.4  rillig _:=	${N::=${N:[1..-2]}} ${TMP::=${VIA}} ${VIA::=${TO}} ${TO::=${TMP}}
     38  1.1  rillig .  include "${.PARSEDIR}/${.PARSEFILE}"
     39  1.4  rillig _:=	${N::+=D} ${TMP::=${VIA}} ${VIA::=${TO}} ${TO::=${TMP}}
     40  1.1  rillig 
     41  1.1  rillig .  for from to in ${FROM} ${TO}
     42  1.1  rillig all::
     43  1.1  rillig 	@echo "Move the upper disk from stack ${from} to stack ${to}."
     44  1.1  rillig .  endfor
     45  1.1  rillig 
     46  1.4  rillig _:=	${N::=${N:[1..-2]}} ${TMP::=${VIA}} ${VIA::=${FROM}} ${FROM::=${TMP}}
     47  1.1  rillig .  include "${.PARSEDIR}/${.PARSEFILE}"
     48  1.4  rillig _:=	${N::+=D} ${TMP::=${VIA}} ${VIA::=${FROM}} ${FROM::=${TMP}}
     49  1.1  rillig .endif
     50