learn prolog now 4

来源:互联网 发布:linux squid 透明代理 编辑:程序博客网 时间:2024/06/05 10:50

prolog 中的list是什么都可以装载的,可以嵌套list,

prolog的list操作符为|

[Head| Tail] = [mia, vincent, jules, yolanda].

Head = mia
Tail = [vincent,jules,yolanda]
yes

变量可以在两边都可以赋值

[X,Y | W] = [[], dead(zed), [2, [b, chopper]], [], Z].
X=[]
Y = dead(zed)
W = [[2,[b,chopper]],[],_8327]
Z = _8327

如果对某些值不关心,可以使用_

[_,X,_,Y|_] = [[], dead(zed), [2, [b, chopper]], [], Z].
X = dead(zed)
Y=[]
Z = _9593

检查X是否在T中。

member(X,[X|T]).
member(X,[H|T]) :- member(X,T).

t doesthis by stepwise breaking down the list into smaller lists, and looking at the first item
of each smaller list. This mechanism that drives this search is recursion, and the reason
that this recursion is safe (that is, the reason it does not go on forever) is that at the end
of the line Prolog has to ask a question about the empty list. The empty list cannot be
broken down into smaller parts, and this allows a way out of the recursion.

a better version

member(X,[X|_]).
member(X,[_|T]) :- member(X,T).

4.2 德文数字到英文数字的转换

tran(eins,one).
tran(zwei,two).
tran(drei,three).
tran(vier,four).
tran(fuenf,five).
tran(sechs,six).
tran(sieben,seven).
tran(acht,eight).
tran(neun,nine).

listtran([],[]).
listtran(X,Y) :- tran(X,Y).
listtran([X|Ta],[Y|Tb]) :- tran(X,Y),listtran(Ta,Tb).


1. Write a 3-place predicate combine1 which takes three lists as arguments and
combines the elements of the first two lists into the third as follows:
?- combine1([a,b,c],[1,2,3],X).
X = [a,1,b,2,c,3]
?- combine1([foo,bar,yip,yup],[glub,glab,glib,glob],Result).
Result = [foo,glub,bar,glab,yip,glib,yup,glob]

答案:

combine([],[],[]).
combine([X|Ta],[Y|Tb],[X,Y|Tc]) :- combine(Ta,Tb,Tc).

2. Now write a 3-place predicate combine2 which takes three lists as arguments
and combines the elements of the first two lists into the third as follows:
?- combine2([a,b,c],[1,2,3],X).
X = [[a,1],[b,2],[c,3]]
?- combine2([foo,bar,yip,yup],[glub,glab,glib,glob],Result).
Result = [[foo,glub],[bar,glab],[yip,glib],[yup,glob]]

combine([],[],[]).
combine([X|Ta],[Y|Tb],[[X,Y]|Tc]) :- combine(Ta,Tb,Tc).

3. Finally, write a 3-place predicate combine3 which takes three lists as arguments
and combines the elements of the first two lists into the third as follows:
?- combine3([a,b,c],[1,2,3],X).
X = [join(a,1),join(b,2),join(c,3)]
?- combine3([foo,bar,yip,yup],[glub,glab,glib,glob],R).
R = [join(foo,glub),join(bar,glab),join(yip,glib),join(yup,glob)]


combine3([],[],[]).
combine3([X|Ta],[Y|Tb],[join(X,Y)|Tc]) :- combine3(Ta,Tb,Tc).

1. Write a predicate mysubset/2 that takes two lists (of constants) as arguments and
checks, whether the first list is a subset of the second.

感觉是错的答案:


subset([],X).
subset(X,[X|Ta]).
subset([X|Ta],[X|Tb]) :- subset(Ta,Tb).
subset([X|Ta],[_|Tb]) :- subset([X|Ta],Tb).





原创粉丝点击