Instantly share code, notes, and snippets.
CreatedFebruary 19, 2009 13:51
Save jrudolph/66925 to your computer and use it in GitHub Desktop.
Scala-Metaprogramming: Towers of Hanoi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
/* | |
* This is the Towers of Hanoi example from the prolog tutorial [1] | |
* converted into Scala, using implicits to unfold the algorithm at | |
* compile-time. | |
* | |
* [1] http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/2_3.html | |
*/ | |
objectTowersOfHanoi { | |
importscala.reflect.Manifest | |
defsimpleName(m:Manifest[_]):String= { | |
valname= m.toString | |
name.substring(name.lastIndexOf('$')+1) | |
} | |
traitNat | |
finalclass_0extendsNat | |
finalclassSucc[Pre<:Nat]extendsNat | |
type_1=Succ[_0] | |
type_2=Succ[_1] | |
type_3=Succ[_2] | |
type_4=Succ[_3] | |
caseclassMove[N<:Nat,A,B,C]() | |
implicitdefmove0[A,B,C](implicit a:Manifest[A],b:Manifest[B]):Move[_0,A,B,C]= { | |
System.out.println("Move from"+simpleName(a)+" to"+simpleName(b));null | |
} | |
implicitdefmoveN[P<:Nat,A,B,C](implicit m1:Move[P,A,C,B],m2:Move[_0,A,B,C],m3:Move[P,C,B,A]) | |
:Move[Succ[P],A,B,C]=null | |
defrun[N<:Nat,A,B,C](implicit m:Move[N,A,B,C])=null | |
caseclassLeft() | |
caseclassCenter() | |
caseclassRight() | |
defmain(args:Array[String]){ | |
run[_2,Left,Right,Center] | |
} | |
} |
Using shapeless I created a version which moves the result to the type.
It obviously ruins the 'self-contained'ness of the gist, but here it is:https://gist.github.com/HusrevAtSky/cae020c79c844e22024c8cd027a5c6ce
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment