Prolog question

Let's assume the result is the third parameter.

a (1, [Hd | Tl], Hd). a (N, [| Tl], Elem): - N> 1, N1 is N - 1, a (N1, Tl, Elem).

I am trying to figure out what this does.

+2


a source to share


1 answer


It gives the Nth element of the list. You can read the definition like this:

a( 1, [Hd | Tl], Hd ).

      

Hd is the first item in the list [Hd | Tl]

, that is, a list starting with Hd followed by a Tl list.



a( N, [ | Tl], Elem ) :- N > 1, N1 is N - 1, a( N1, Tl, Elem).

      

Elem is the Nth element of the list if and only if it is the N1

th element of its tail, where N1

- N-1

.

+1


a source







All Articles