1
votes

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?

1
Right now, your 3rd argument to vals/3 doesn't really do anything. You could make it be the list you want. If the head of [H|T] matches the first element of the head of [(H,C)|L] what do you think the head of the 3rd argument should be? And where do you think the tail of the 3rd argument should come from (or how should it be determined)?lurker
The head of third argument should be C, but I don't know how to recursively add elements to the list after each call.dreamPr
The result then would look like [C|R]. You just have to tell it how to get the tail of the result (R) from the tails of the inputs. It's easier than you think.lurker
Why is your first argument a list, while you are only using the head? Shouldn't you add a case when not all tupples in the second list start with 1 in your example?Sam Segers
This is a base case, list can also be longer and contain more elements. And case when not all tuples in the second list start with 1: vals([H|T],[(O,_)|L],K)) :- H\=O,foundValues2([H|T],L,K)dreamPr

1 Answers

1
votes

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