[英]Prolog Programming List Arithmetic
Here is my code to make a countdown procedure which when I type in countdown(5,L).
这是我进行倒数计时的代码,当我输入
countdown(5,L).
should return L = [5,4,3,2,1]
and countdown(5,[5,4,3,2,1])
should return true
. 应该返回
L = [5,4,3,2,1]
和countdown(5,[5,4,3,2,1])
应该返回true
。
The input countdown(5,L).
输入
countdown(5,L).
returns 回报
ERROR: is/2: Type error:
[]' expected, found
[5,4]' ("x" must hold one character)错误:is / 2:类型错误:
[]' expected, found
[5,4]'(“ x”必须包含一个字符)
which shows me my program is beginning to create the list. 这说明我的程序正在开始创建列表。
%countdown
countdown(1,[1]).
countdown(A,L) :-
concat([],[A],Z),
makeList(Z,A,List),
L is List.
makeList(X,Y,List) :-
N1 is Y-1,
N1 > 0,
concat(X,[N1],Z),
List is Z,
makeList(Z,N1,List).
concat([],Y,Y).
concat([H|X],Y,[H|Z]):-
concat(X,Y,Z).
Why so difficult? 为什么这么难?
countdown(1, [1]).
countdown(N, [N|T]) :-
N1 is N-1,
countdown(N1, T).
Some comments on your code: 关于您的代码的一些注释:
countdown/2
, clause 2, line 1: countdown/2
,第2条,第1行:
concat([],[A],Z)
is completely unnecessary. concat([],[A],Z)
完全没有必要。 At the end of this exercise, Z
is unified with [A]
. 在本练习的最后,
Z
与[A]
统一。
countdown/2
, clause 2, line 3:** countdown/2
,第2条,第3行:**
As was pointed out, is/2
evaluates the right hand term as an arithmetic expression and unifies the result with the left-hand side. 如所指出的,
is/2
将右手项作为算术表达式求值,并将结果与左手统一。 This should be L = List
. 这应该是
L = List
。
Even better, just change the line above from makeList(Z,A,List)
to makeList(Z,A,L)
. 更好的是,将上面的行从
makeList(Z,A,List)
更改为makeList(Z,A,L)
。
But this is overly complicated. 但这过于复杂。 If one was to take your general approach, you could do it thusly:
如果要采用一般方法,则可以这样做:
count_down(N,L) :- % To count down to 1 from N,
integer(N) , % N must first be integral
N > 0 , % and positive
range(N,1,L). % Then you just need to generate the desired range.
range/3
could be implemented simply as this: range/3
可以这样简单地实现:
range( X , Y , [X] ) :- X = Y .
range( X , Y , [X|Xs] ) :- X > Y , X1 is X-1 , range(X1,Y,Xs) .
range( X , Y , [X|Xs] ) :- X < Y , X1 is X+1 , range(X1,Y,Xs) .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.