Solving puzzles is a challenge developers tend to enjoy and provides points of comparison between different programming languages. Two puzzles are presented here to show eXPL dealing with challenges well known to the computing community: "Towers of Hanoi" and Sudoku.
Towers of Hanoi
Towers of Hanoi is often used as an example of recursion where a function calls itself one or more times to progress to a result. The puzzle consists of three rods and a number of disks of different sizes, which can slide onto any rod. The initial configuration is a stack of disks on one rod and the aim is to move the stack to the adjacent rod while keeping to the rules governing the placement of the disks:
- For each move, take the disk from the top of one of the stacks and place it on top of another stack.
- No disk may be placed on top of a smaller disk.
As the solution depends entirely on recursion, the eXPL program contains a single calculator called "tower_of_hanoi". This can be viewed in application TowersOfHanoi of tutorial15:
(
? n == 1
{
" to rod ", to_rod)
: n == 1,
<- tower_of_hanoi(disk=n - 1,
to=aux_rod, aux=to_rod),
" to rod ", to_rod),
to=to_rod, aux=from_rod)
Two aspects of interest with recursion are how to set initial parameters to start it off and and how to exit from the recursion. The first aspect is taken care of by using parameters. Three template parameters set the names of the rods:
The disk number is supplied as a query parameter so that there can be queries for a specific number of disks:
query towers_of_hanoi2(tower_of_hanoi)(n=2);
query towers_of_hanoi3(tower_of_hanoi)(n=3);
The initial parameters are paired to calculator variables by name, but this is not possible for the recursion parameters, so
they are paired by position. For example, the first parameter, the disk number "n", is set in the recursion
call to disk=n - 1, which works because it is the first parameter.
The second aspect of interest is the exit from the recursion and this is handled by a short cut expression which fires when the disk number gets to 1:
Sudoku
The next program is inspired by a Prolog Sudoku puzzle from Yevgeniy Brikman in his Six programming paradigms that will change how you think about coding". His sudoku solver uses the Prolog syntax to describe the puzzle and what constitutes a solution. He explains how to run the solver and the expected solution as follows:
| | ?- sudoku( | [_, _, 2, 3, |
| _, _, _, _, | |
| _, _, _, _, | |
| 3, 4, _, _], | |
| Solution). |
S = [4,1,2,3,2,3,4,1,1,2,3,4,3,4,1,2]
The program is concise but delegates the actual work of solving the puzzle to a "Fixed Domain" library, which includes a function to test if all members of a particular grouping are all different.
