I have programmed many things in many programming languages, and Prolog is not one of those languages. I am supposed to write a program that will solve a sudoku puzzle when given a puzzle representation as input.
My idea:
Store all supplied numbers in a list of lists (list of rows), and brute force the possible options until one fits (I know, it’s not the most elegant, but I don’t have a lot of time to spend writing out the logic to solve the puzzle conventionally). But, being new to Prolog, I am having some difficulty understanding the way of going about things. The input is given in a text file in the form of rows looking like
1-2---34-
-34--1-5-
and so on and so forth. My code to read and print the file is:
readPuzzle(File) :-
see(File),
repeat,
get_char(X),
(X = end_of_file, !
;
write(X),
fail
),
seen.
This works all well and good. So let’s say I try to build this list by adding a W = []
just above see(File) and replace write(X) with W = [W|X]. From my experience, this should create a long list of all of the chars supplied from the text file.
It doesn’t.
Someone please either
- tell me a better more prological way of accomplishing the task ahead of me
- explain how I can work around this.
There are several ways of accomplish the specification reading. If you are willing to reuse your code, I would suggest to use assertz:
and use
to get the list of chars read, then you will need to split the list in lines, discarding lines’ separators.
Otherwise, instead of asserting/retracting, we can use service predicate that collects more structured input, and constraints length while reading:
For an example of how this works in SWI-Prolog:
update
Here is another way, using accumulators to collect structured input and size..