[英]Prolog predicate to multiply two lists (representing unary numbers)
I want to write a code that multiplies lists representing a number, like:我想编写一个代码来乘以代表数字的列表,例如:
?- times([1,1,1], [1,1], Res). ?- 次 ([1,1,1], [1,1], Res)。
Res = [1,1,1,1,1,1]. Res = [1,1,1,1,1,1]。
times([], _, []). % base case
times([_|T], Lis, [Lis|H]) :-
times(T, Lis, H).
I already have the code above and it kinda does what I want but not really.我已经有了上面的代码,它有点像我想要的,但不是真的。 For example when asking:
例如在询问时:
?- times([1,1,1], [1,1], Res) ?- 次 ([1,1,1], [1,1], Res)
Res = [[1,1],[1,1],[1,1]]. Res = [[1,1],[1,1],[1,1]]。
The idea is there, but I just don't know how to fix that, I understand why it's happening (I'm adding a list as head), so I just wondered if anybody could help me.想法就在那里,但我只是不知道如何解决这个问题,我明白为什么会这样(我添加了一个列表作为头部),所以我只是想知道是否有人可以帮助我。
Thanks in advance.提前致谢。
[Lis|H]
will use Lis
as first element, regardless whether Lis
is a list or not. [Lis|H]
将使用Lis
作为第一个元素,无论Lis
是否为列表。 You should take a look at append/3
[swi-doc] for example to append two lists:你应该看看
append/3
[swi-doc]例如到 append 两个列表:
times([], _, []).
times([_|T], Lis,
R) :-
append(
Lis,
H,
R),
times(T, Lis,
H).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.