The Towers of Hanoi in Erlang

18 August, 2009 (22:34) | Programming, Erlang

I’m just playing with Erlang, below is my attempt at solving the Towers of Hanoi puzzle using it. Call it using hanoi:hanoi([1,2,3,4,5,6],[],[]) (a valid starting position is assumed).

-module(hanoi).
-export([hanoi/3]).

hanoi(A,B,C) ->
	Disk=lists:max(A),
	move(Disk,A,B,C).

move(Disk,[Disk|Source],Dest,Temp)->
	[Source,[Disk|Dest],Temp];

move(Disk, Source, Dest, Temp) ->
	[S1,T1,D1]=move(Disk-1,Source,Temp,Dest),
	[S2,D2,T2]=move(Disk,S1,D1,T1),
	[T3,D3,S3]=move(Disk-1,T2,D2,S2),
	[S3,D3,T3].

Write a comment