]> Repositorios git - scryer-prolog.git/commitdiff
ADDED: nth0/3, relating indices to list elements
authorMarkus Triska <[email protected]>
Tue, 28 Apr 2020 15:42:12 +0000 (17:42 +0200)
committerMarkus Triska <[email protected]>
Tue, 28 Apr 2020 15:59:49 +0000 (17:59 +0200)
src/prolog/lib/lists.pl

index cded47467d93422843b6030610f0d38e5f03b14e..693ccc1067eb43b941da08e5435ab1f3f430c7d8 100644 (file)
@@ -1,7 +1,7 @@
 :- module(lists, [member/2, select/3, append/2, append/3, foldl/4, foldl/5,
                  memberchk/2, reverse/2, length/2, maplist/2,
                  maplist/3, maplist/4, maplist/5, maplist/6,
-                 maplist/7, maplist/8, maplist/9, same_length/2,
+                 maplist/7, maplist/8, maplist/9, same_length/2, nth0/3,
                  sum_list/2, transpose/2, list_to_set/2]).
 
 
@@ -177,3 +177,26 @@ unify_same(E-V, Prev-Var, E-V) :-
             Var = V
         ;   true
         ).
+
+
+nth0(N, Es, E) :-
+        can_be(integer, N),
+        can_be(list, Es),
+        (   integer(N) ->
+            nth0_index(N, Es, E)
+        ;   nth0_search(N, Es, E)
+        ).
+
+nth0_index(0, [E|_], E) :- !.
+nth0_index(N, [_|Es], E) :-
+        N > 0,
+        N1 is N - 1,
+        nth0_index(N1, Es, E).
+
+nth0_search(N, Es, E) :-
+        nth0_search(0, N, Es, E).
+
+nth0_search(N, N, [E|_], E).
+nth0_search(N0, N, [_|Es], E) :-
+        N1 is N0 + 1,
+        nth0_search(N1, N, Es, E).