简体   繁体   中英

Recursively create list in Prolog

I have code in PROLOG:

vals(_,[],_).
vals([H|T],[(H,C)|L],K) :- vals([H|T],L,(K,C)).

This code receivers list and list of tuples, for example:

 vals([1],[(1,4),(1,2)],X).

I check if element from first list is equal to some tuples first element from the other list. In this case foundValues will return true, because 1 is equal to each tuples first element. This works fine, but instead of returning true/false, in resulting list I want to return all second element of each tuple where its first element is equal to the element from list. In this case X should be [4,2]. I am trying to do this with (K,C), but no success. So, the question is - How to return list?

Here's an example on how to append to the list, just for 1 element.

Three cases:

  • For an empty list
  • When the element matches the first entry of the tupple
  • When the element not matches

Starting from this you should be able to create your example.

vals(_,[],[]).
vals(H,[(H,C)|L],[C|K]) :- vals(H,L,K).
vals(H,[(H2,_)|L],K) :- 
    H \= H2,
    vals(H,L,K).

Example:

vals(1,[(1,2),(1,3)],X).
X = [2, 3] ;
false.

Extra:

  • Consider placing a cut in case 2.
  • Consider rewrite this with an accumulator

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