tags:

views:

86

answers:

1
+2  Q: 

Prolog Question

Assume the third parameter is the result.

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

I'm trying to understand what this does....

+1  A: 

It gives the Nth element of a list. You can read the definition as follows:

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

Hd is the 1st element of the list [Hd | Tl], i.e. the list that starts with Hd, followed by the list Tl.

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

Elem is the Nth element of a list if and only if it is the N1th element of its tail, where N1 is N-1.

sepp2k