Prolog Question
Assume the third parameter is the result.
a( 1, [Hd | Tl], Hd ). a( N, [ | Tl],开发者_StackOverflow Elem ) :- N > 1, N1 is N - 1, a( N1, Tl, Elem).
I'm trying to understand what this does....
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 N1
th element of its tail, where N1
is N-1
.
精彩评论