新しい nth1 を定義してみよう。
ウェブを検索すると、普通 nth1(nth1_A) は、次のように定義されています。
■ nth1(nth1_A) code
nth1_A(1, [A|_], A). nth1_A(N, [_|L], A) :- N > 1, N1 is N - 1, nth1_A(N1, L, A).
実行してみますと、逆方向では失敗します。
?- nth1_A( 3, [a,b,c,d,e,f], P ). P = c ; false. ?- nth1_A( I, [a,b,c,d,e,f], c ). ERROR: >/2: Arguments are not sufficiently instantiated
♪ それで、双方向に成功する nth1(nth1_B)を作りました。
■ nth1(nth1_B) code
nth1_B( Index, List, Item ) :- nth1_B( Index, List, Item, 1 ). nth1_B( I, [A|_], A, I ). nth1_B( I, [_|L], A, N ) :- N1 is N + 1, nth1_B( I, L, A, N1 ).
実行してみます。
?- nth1_B( 3, [a,b,c,d,e,f], P ). P = c ; false. ?- nth1_B( I, [a,b,c,d,e,f], c ). I = 3 ; false. ?-
双方向に成功する 新しい nth1 が、定義できました。