Last active
June 8, 2020 20:42
-
-
Save dirkschumacher/e1372d5ca397ab3ca6bd3cfdc0ed4694 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
library(logician) | |
# Towers of Hanoi | |
# https://en.wikipedia.org/wiki/Tower_of_Hanoi | |
# Original Prolog Implementation: | |
# https://www.cs.toronto.edu/~sheila/384/w11/simple-prolog-examples.html | |
database <- logician_database( | |
# no `is` operator yet, so we have to define all valid numbers | |
num(1),num(2),num(3),num(4),num(5), | |
num(6),num(7),num(8),num(9), | |
move(1, X, Y, Z) := r( | |
is.character(print(paste0("Move top disk from ", X, " to ", Y)))), | |
move(N, X, Y, Z) := num(N) && | |
r(N > 1) && num(M) && | |
r(M == N - 1) && | |
move(M, X, Z, Y) && | |
move(1, X, Y, Temp) && | |
move(M, Z, Y, X) | |
) | |
# solve an instance where 3 disks are on the left peg. | |
iter <- logician_query(database, move(3, left, right, center)) | |
iter$next_value() | |
#> [1] "Move top disk from left to right" | |
#> [1] "Move top disk from left to center" | |
#> [1] "Move top disk from right to center" | |
#> [1] "Move top disk from left to right" | |
#> [1] "Move top disk from center to left" | |
#> [1] "Move top disk from center to right" | |
#> [1] "Move top disk from left to right" | |
#> TRUE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment