我正在尝试编写一个填字游戏解算器我有这个代码,但我无法理解它的一些部分:
size(5).
black(1,3).
black(2,3).
black(3,2).
black(4,3).
black(5,1).
black(5,5).
words([do,ore,ma,lis,ur,as,po, so,pirus, oker,al,adam, ik]) .
:- use_module(library(lists),[nth1/3, select/3]).
crossword(Puzzle) :-
words(WordList),
word2chars(WordList,CharsList),
make_empty_words(EmptyWords) ,
fill_in(CharsList,EmptyWords),
word2chars(Puzzle,EmptyWords).
word2chars([],[]).
word2chars([Word|RestWords] ,[Chars|RestChars] ) :-
atom_chars(Word,Chars),
word2chars(RestWords,RestChars).
fill_in([],[]).
fill_in([Word|RestWords],Puzzle) :-
select(Word,Puzzle,RestPuzzle),
fill_in(RestWords,RestPuzzle).
make_empty_words(EmptyWords) :-
size(Size),
make_puzzle(Size,Puzzle),
findall(black(I,J),black(I,J),Blacks) ,
fillblacks(Blacks,Puzzle),
empty_words(Puzzle,EmptyWords).
make_puzzle(Size,Puzzle) :-
length(Puzzle,Size),
make_lines(Puzzle,Size).
make_lines([],_).
make_lines([L|Ls],Size) :-
length(L,Size),
make_lines(Ls,Size).
fillblacks([],_).
fillblacks([black(I,J)|Blacks],Puzzle) :-
nth1(I,Puzzle,LineI),
nth1(J,LineI,black),
fillblacks(Blacks,Puzzle).
empty_words(Puzzle,EmptyWords) :-
empty_words(Puzzle,EmptyWords,TailEmptyWords),
size(Size),
transpose(Size,Puzzle,[],TransposedPuzzle),
empty_words(TransposedPuzzle,TailEmptyWords,[] ).
empty_words([],Es,Es).
empty_words([L|Ls],Es,EsTail) :-
empty_words_on_one_line(L,Es,Es1) ,
empty_words(Ls,Es1,EsTail).
empty_words_on_one_line([], Tail, Tail).
empty_words_on_one_line([V1,V2|L],[[V1,V2|Vars]|R],Tail) :-
var(V1), var(V2), !,
more_empty(L,RestL,Vars),
empty_words_on_one_line(RestL,R,Tail) .
empty_words_on_one_line([_| RestL],R, Tail) :-
empty_words_on_one_line(RestL,R,Tail) .
more_empty([],[],[]).
more_empty([V|R],RestL,Vars) :-
( var(V) ->
Vars = [V|RestVars],
more_empty(R,RestL,RestVars)
;
RestL = R,
Vars = []
).
transpose(N,Puzzle,Acc,TransposedPuzzle) :-
( N == 0 ->
TransposedPuzzle = Acc
;
nth_elements(N,Puzzle,OneVert),
M is N - 1,
transpose(M,Puzzle,[OneVert|Acc], TransposedPuzzle)
).
nth_elements(_,[],[]).
nth_elements(N,[X|R],[NthX| S]) :-
nth1(N,X,NthX),
nth_elements(N,R,S).
Run Code Online (Sandbox Code Playgroud)
此代码用于解决这样的填字游戏:
符号;
->
用于什么?
我的主要问题是理解规则,transpose和more_empty.任何解释,以帮助我理解代码将不胜感激.
除了 Josh 和 Avi Tshuva 的正确答案指出a -> b ; c
“if a then b else c”之外,我还想解释一下 和->
是;
可以单独使用的单独运算符。
;
是逻辑或,即 逻辑“或”。所以x; y
意思是“x或y”。这使得条件语句有点混乱,因为a -> b ; c
读起来像“a 暗示 b 或 c”,这显然不是它的意思!即使您像“(a 暗示 b) 或 c”一样将其括起来,您也会得到与条件语句不同的含义,因为在这种错误的解释中,即使 (a 暗示 b) 成功,也将始终尝试 c。
区别在于->
有一些“非逻辑”语义。来自SWI-Prolog 文档:
:条件 -> :动作
如果-那么和如果-那么-否则。该->/2
构造致力于在其左侧做出的选择,破坏子句内创建的选择点(由;/2
)或由该子句调用的目标。与 不同!/0
,谓词的选择点作为一个整体(由于多个子句)不会被破坏。;/2
和 的组合的->/2
作用就好像定义为:
If -> Then; _Else :- If, !, Then. If -> _Then; Else :- !, Else. If -> Then :- If, !, Then.
请注意, 的(If -> Then)
作用就像(If -> Then ; fail)
,如果条件失败,则构造会失败。这种不寻常的语义是 ISO 和所有事实上的 Prolog 标准的一部分。
(请注意,在上面的引用中,If
等Then
都是变量!)
所以要小心任何带有隐式剪切的东西!