learn prolog now 4

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).





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值