简体   繁体   中英

Return values in Prolog predicate

My predicate only returns a solution forcibly (when adding write(L)). The result is always an empty list.

I ask for help in solving this problem.

%:- dynamic myList/2.
 
myList('1', '').
myList('2', '1').
myList('3', '1').
myList('4', '1').
myList('5', '1').
myList('6', '1').
myList('7', '1').
myList('8', '1').
myList('9', '1').
myList('10', '4').
myList('11', '5').
myList('12', '5').
myList('13', '6').
myList('14', '6').
myList('15', '6').
myList('16', '6').

a([],L):- write(L).
a([H|T], L1):- findall( Y, myList( Y, H), L2),   
    append(L1, [H|L2], L3),
    a(T, L3).

在此处输入图像描述

a([H|T], L1) says effectively that L1 will be the output. That means L1 has to end up with the complete list in it. You can't then go and append things onto L1 to make L2 and L3; anything added on to L1 will just be lost. You need to go the other way and append things together to make L1 and build it up. Building up from from an empty list input and output base case.

nums_chain([], []).
nums_chain([H|T], Chain) :-
    findall(E, myList(E, H), Extras),
    append([H], Extras, ChainHead),
    append(ChainHead, ChainTail, Chain),
    nums_chain(T, ChainTail).

(I would like a syntax like [ChainHead|ChainTail] or [H,Extras|ChainTail] but those would be nested lists so they won't work here).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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