Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog, access specific member of list?

Tags:

Can anyone tell me how to access a specific member of a list in prolog? Say for example I need to access the 3rd or 4th element of a list passed into a rule?

like image 751
David Carpenter Avatar asked Oct 17 '12 16:10

David Carpenter


People also ask

How do you access list elements in Prolog?

Unlike arrays in other programming languages where we can directly access any element of the array, prolog lists allow direct access of the first element only which is denoted as Head. Therefore we can write a prolog list as : [Head | Rest], where Rest is the rest of the list excluding the first element Head.

How do I iterate through a list in Prolog?

Generally, you do not iterate in Prolog. Instead, you write a rule with a pair of recursive clauses, like this: dosomething([]). dosomething([H|T]) :- process(H), dosomething(T).

What is Maplist in Prolog?

maplist(Goal, List) is true if and only if Goal can be successfully applied to List. If Goal fails for any of List's elements, maplist fails.

How do you get the head and tail of a list in Prolog?

In Prolog list elements are enclosed by brackets and separated by commas. Another way to represent a list is to use the head/tail notation [H|T]. Here the head of the list, H, is separated from the tail of the list, T, by a vertical bar.


1 Answers

nth0(Ind, Lst, Elem) or nth1(Ind, Lst, Elem) with SWI-Prolog, nth0 the first element has the index 0.

For example,

nth0(3, [a, b, c, d, e], Elem). %Binds d to Elem nth1(3, [a, b, c, d, e], Elem). %Binds c to Elem  nth0(Ind, [a, b, c, d, e], d).  %Binds 3 to Ind nth0(3, [a, b, c, X, e], d).    %Binds d to X  nth0(3, [a, b, c, d, e], c).    %Fails. 
like image 140
joel76 Avatar answered Sep 21 '22 19:09

joel76