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?
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With