STOPIMACODER
STOPIMACODER

Reputation: 822

Iterating through 2D list in prolog?

I'm trying to iterate through a 2D list in prolog. So let's assume we have a list of

[item(Key,Value), ......., (item(Key,Value)]

I know we can go through a list by omitting the head element through:

member2(X, [H|T]):-
    member2(X, T).

But i do not know how to iterate through the Key/Value list.

Upvotes: 1

Views: 239

Answers (1)

Ch3steR
Ch3steR

Reputation: 20669

You want to search if Key is present in the list or not. If yes then I have linked the code below.

searchKey(Key,[(Key,Value)|_]):- write(Key) , write('-->'), write(Value) , !.
searchKey(Key,[_|T]):- searchKey(Key,T).

OUTPUT

?- searchKey(3,[(1,99),(2,98),(3,97),(4,96)]).
3-->97

if you search for a element that doesnt exist then it wil return false.

?- searchKey(5,[(1,99),(2,98),(3,97),(4,96)]).
   false

Hope this helped you. If this is not what you've asked. Then try explaining the question more clearly.

Upvotes: 1

Related Questions