开发者

Prolog Question

开发者 https://www.devze.com 2022-12-29 04:55 出处:网络
Assume the third parameter is the result. a( 1, [Hd | Tl], Hd ). a( N, [ | Tl],开发者_StackOverflow Elem ) :-

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 N1th element of its tail, where N1 is N-1.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号