Prolog/Lists.pro

94 lines
1.9 KiB
Prolog
Raw Normal View History

2023-06-05 17:01:54 +00:00
% iterate over list in sucessive order
% prints each element
%
% example: iter_nth([1,2,3,4,5,6,7,8,9])
% output: [1,2,3,4,5,6,7,8,9]
iter([]).
iter([H|T]):-writeln(H), iter(T).
% iterate over list in reverse order
% prints each element
%
% example: iter_nth([1,2,3,4,5,6,7,8,9])
% output: [9,8,7,6,5,4,3,2,1]
iter_rev([A]):-writeln(A).
iter_rev([H|T]):-iter_rev(T), writeln(H).
% prints every 2nd element from the supplied list
iter_every_2nd([]).
iter_every_2nd([_|[H2|T]]):-writeln(H2), iter_every_2nd(T).
% iterate over every nth element in the list
%
% example: iter_nth([1,2,3,4,5,6,7,8,9], 3)
% output: [3, 6, 9]
iter_nth([], _, _).
iter_nth([H|T], E, 0):-
R is E - 1,
iter_nth(T, E, R),
writeln(H).
iter_nth([_|T], E, L):-
R is L - 1,
iter_nth(T, E, R).
iter_nth(L, N):-
R is N - 1,
iter_nth(L, N, R).
% iterate over all elements with an even index
iter_even(L):-iter_nth(L, 2).
% iterate over all elements with an odd index
iter_odd(L):-iter_nth(L, 2, 0).
% counts the amount of items in the supplied list
%
% example: len([1,2,3,4,5,6], X)
% output: X = 6
len([], L):-L is 0.
len([_|T], L):-
len(T, Tmp),
L is Tmp + 1.
% count the amounts an element `E` is present in the supplied list
%
% example: count([a,b,c,a], a, X)
% output: X = 2
count([], _, L):-L is 0.
count([H|T], E, L):-
H == E,
count(T, E, R),
L is R + 1.
count([_|T], E, L):-
count(T, E, R),
L is R.
% return the nth element of the supplied list.
% indexing starts with 0
%
% example: nth([a,b,c,d,e], 3, X)
% output: X = d
nth([],_).
nth([H|_], 0, O):-O is H.
nth([_|T], C, O):-
C1 is C - 1,
nth(T,C1, K),
O is K.
% return the index of the first occurance of the element
% in a list
% indexing starts with 0
%
% example: indexof([0,1,3,4,5,6,7,8,9], 3, X)
% output: X = 2
indexof([],_,C):-C is 0.
indexof([H|_],E,C):-
H == E,
C is 0.
indexof([_|T],E,C):-
indexof(T,E,R),
C is R + 1.