将差异零附加到 Prolog 中的列表 [英] Append difference zero to list in Prolog

查看:48
本文介绍了将差异零附加到 Prolog 中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要取NUM1ANSNum2的长度差 &ANS 并在 NUM1NUM2 后附加等于长度差的零.我很难做到这一点.

I need to take the difference of length of NUM1 and ANS and Num2 & ANS and append zero equal to the difference of length to both NUM1 and NUM2. I have trouble doing that.

sum(NUM1, NUM2, ANS):-
    comp(NUM1, ANS),
    comp(NUM2, ANS),
    % Arguments: Carry's from right and to left both 0 and all available digits
    add( NUM1, NUM2, ANS, 0, 0, [0,1,2,3,4,5,6,7,8,9], _).

add( [], [], [], C, C, Digits, Digits).
comp(NUM, ANS).

comp(NUM, ANS, OUT):-
    length(NUM, L1),
    length(ANS, L2),
    LI = [0],
    (L1 < L2 -> OUT = appendlist(LI, NUM, NUM)).

appendlist([],X,X).
appendlist([X|Y],Z,[X|W]) :- append(Y,Z,W).

推荐答案

这里是谓词的代码,如果列表 Out 中的所有列表都是列表 In 中的零填充列表,则该谓词为真:

Here is the code for predicate that is true if all lists in list Out are zero-padded lists from list In:

same_length_padded_lists(In, Out) :-
    findall(Length, (nth1(_,In,List), length(List, Length)), Lengths),
    max_list(Lengths, Max),
    length(In, Lists),
    findall(NewList, (between(1, Lists, Index), length(NewList, Max), nth1(Index, In, OL), append(Padding, OL, NewList), maplist(=(0), Padding)), Out).

样本输入和输出:

?- same_length_padded_lists([[1,2], [1,2,3], [1], [5,3]], X).
X = [[0, 1, 2], [1, 2, 3], [0, 0, 1], [0, 5, 3]].

OP 的问题:

?- same_length_padded_lists([[T,W,O], [T,W,O], [F,O,U,R]], X).
X = [[0, _G6258, _G6261, _G6264], [0, _G6243, _G6246, _G6249], [_G6225, _G6228, _G6231, _G6234]].

如您所见,您可以一次填充任意数量的列表.

As you see, you can pad with zeros any number of lists at once.

这篇关于将差异零附加到 Prolog 中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆