将列表转换为序言中的另一个列表 [英] Translating a list to another list in prolog
问题描述
我试图在 Prolog 中编写一个简单的代码,将一个列表转换为另一个列表.例如,如果我们调用 listtrans([a,b,c],L)
,L
将变成 [1,2,3]
.(a,b,c 替换为 1,2,3).但是我在最后一行遇到了语法错误.问题是什么?这是我的代码:
I Tried to write a simple code in Prolog which translate a list to another list. for instance, if we call listtrans([a,b,c],L)
, L
will become [1,2,3]
. (a,b,c is replaced with 1,2,3). But i faced with a syntax error in last line. what is the problem? here is my code:
trans(a,1).
trans(b,2).
trans(c,3).
listtrans([],L).
listtrans([H|T],L1):-
trans(H,B),
append(B,L,L2),
listtrans(T,L2).
推荐答案
该错误很可能是因为在您的代码中:
The error is very likely because in your code:
listtrans([H|T],L1):-
trans(H,B),
append(B,L,L2),
listtrans(T,L2).
变量 L1
在头部声明,但没有在任何地方引用:你拼错了什么?
the variable L1
is declared in the head, but not referenced anywhere: you mispelled something?
无论如何,你的代码是行不通的.
Anyway, your code is not going to work.
此外,将 append/3
用于此类易于通过递归定义的任务被认为糟糕(也是因为您从中获得的性能不佳).
Moreover, using append/3
for this kind of tasks which are easily defined by recursion is considered terrible (also because of the bad performance you get out of it).
将函数应用于列表很简单.你已经知道在序言中你不写 Y = f(X)
而是声明 X
和 之间的函数关系Y
为:f(X, Y).
.(这基本上就是你对 trans(X,Y)
所做的).
Applying a function to a list is straightforward. You already know that in prolog you don't write Y = f(X)
but rather declare the functional relation between X
and Y
as: f(X, Y).
. (That's basically what you did with trans(X,Y)
).
现在是(简单的)递归公式:
Now the (easy) recursive formulation:
- 转换后的空列表就是空列表
[X|Xs]
的变换是[Y|Ys]
如果trans(X,Y)
并且我们递归地变换Xs
到Ys
- the transformed empty list is the empty list
- the transformation of
[X|Xs]
is[Y|Ys]
iftrans(X,Y)
and we recursively transformXs
intoYs
或在序言中表示:
listtrans([],[]).
listtrans([X|Xs],[Y|Ys]) :- trans(X,Y), listtrans(Xs,Ys).
我建议您阅读立即学习 Prolog 的前 4 章以更好地了解这些概念.
I recommend you reading the first 4 chapters of Learn Prolog Now to better understand these concepts.
这篇关于将列表转换为序言中的另一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!