Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.