简体   繁体   English

列表大小乘法

[英]Lists size multiplication

I'm new to Prolog and I'm trying to get my head around lists.我是 Prolog 的新手,我正在尝试了解列表。 The problem I'm struggling with is: Given numbers in the form of lists (1 : [x], 3: [x, x, x]), implement the 'times' predicate /3.我正在努力解决的问题是:给定列表形式的数字 (1 : [x], 3: [x, x, x]),实现'times'谓词 /3。 Eg: times([x, x], [x, x, x], R).例如:times([x, x], [x, x, x], R)。 R = [x, x, x, x, x, x]. R = [x, x, x, x, x, x]。

The plus, and successor predicates where 2 previous points of the exercise.加号和后继谓词表示练习的前 2 点。 I know I'm not using the successor predicate, but it didn't seem that useful later on.我知道我没有使用后继谓词,但后来似乎没有那么有用。

This is what i've tried so far这是我迄今为止尝试过的

successor([], [x]).
successor([X|T], R) :- 
    append([X|T], [X], R).

plus(L1, L2, R) :- append(L1, L2, R).

times([], _, []).
times(_, [], []).
times([_], L, L).
times(L, [_], L).
times([_|T], L2, R) :- plus(L2, R, RN),
    times(T, L2, RN).

The output is: R is [].输出是:R是[]。

I think you make things too complicated here.我认为你在这里把事情搞得太复杂了。 You can define successor as:您可以将successor定义为:

successor(T, [x|T]).

We can define plus/3 as:我们可以将plus/3定义为:

plus([], T, T).
plus([x|R], S, [x|T]) :-
    plus(R, S, T).

This is more or less the implementation of append/3 , except that here we check if the first list only contains x .这或多或少是append/3的实现,除了这里我们检查第一个列表是否只包含x

For times/3 we know that if the first item is empty, the result is empty:对于times/3我们知道如果第一项为空,则结果为空:

times([], _, []).

and for a times/3 where the first item has shape [x|R] , we need to add the second item to the result of a call to times/3 with R :对于第一项具有形状[x|R]times/3 ,我们需要将第二项添加到使用R调用times/3的结果中:

times([x|R], S, T) :-
    times(R, S, T1),
    plus(S, T1, T).

So putting it all together, we obtain:所以把它们放在一起,我们得到:

successor(T, [x|T]).

plus([], T, T).
plus([x|R], S, [x|T]) :-
    plus(R, S, T).

times([], _, []).
times([x|R], S, T) :-
    times(R, S, T1),
    plus(S, T1, T).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM