有幾種方法可以完成規範閱讀。如果你願意重用你的代碼,我會建議使用assertz:
:- dynamic onechar/1.
readPuzzle(File) :-
see(File),
repeat,
get_char(X),
(X = end_of_file, !
;
asssertz(onechar(X)), % write(X),
fail
),
seen.
,並使用
..., findall(L, retract(onechar(C)), Cs), ...
得到字符的列表讀取,那麼你就需要分割的行列表,丟棄行的分隔符。
否則,而不是斷言/收縮,我們可以使用的服務斷言,收集更多的結構化輸入和約束長度,同時閱讀:
readPuzzle(File, Puzzle) :-
see(File),
length(Puzzle, 9), % this allocates a list of unbound variables
maplist(read_a_line, Puzzle),
seen.
read_a_line(Line) :-
length(Line, 9),
maplist(get_char, Line),
get_char(_). % get rid of nl
對於如何工作的SWI-Prolog的一個例子:
?- length(L,9),see(user),maplist(get,L),seen.
|: 987654321
L = [57, 56, 55, 54, 53, 52, 51, 50, 49].
更新
這裏是另一種方式,用accumulato RS收集結構化輸入和大小..
readPuzzle(File, Puzzle, Length) :-
see(File),
readLines([], 0, Puzzle, Length),
seen.
readLines(SoFar, CountSoFar, Lines, CountLines) :-
get_char(C), % lookahead
C \= end_of_file,
readLine(C, [], Line),
M is SoFar + 1,
readLines([Line|SoFar], M, Lines, CountLines).
readLines(Lines, TotLines, Lines, TotLines).
readLine(C, Line, Line) :-
C == 10.
readLine(C, SoFar, Line) :-
get_char(S),
readLine(S, [C|SoFar], Line).
這有助於TON謝謝你現在說,我不知道這個數獨題是什麼規模,你會如何保持多少個字符之前被讀取的軌道說「。 \ n'被擊中了嗎?只要做一些像你在這裏給出的東西,並提供一個!當'\ n'被擊中,然後得到長度..? – 2012-04-27 06:04:21
我會補充另一種方式,看到更新的答案 – CapelliC 2012-04-27 06:11:23
啊啊謝謝太多了!你不知道這有多大的幫助。Prolog對我來說是非常陌生的.. – 2012-04-27 06:33:14