Skip to content

Instantly share code, notes, and snippets.

@Voltra
Last active October 8, 2019 11:08
Show Gist options
  • Save Voltra/a74a6c5e4a3edf9003b505db7be10196 to your computer and use it in GitHub Desktop.
Save Voltra/a74a6c5e4a3edf9003b505db7be10196 to your computer and use it in GitHub Desktop.
First steps with HOP in prolog
last([X], X).
last([_|T], R) :- last(T, R).
first([H|_], H).
concat([], X, X).
concat([H|T], Y, [H|R]) :- concat(T, Y, R).
map(_, [], []).
map(F, [H|T], [R|RT]) :- call(F, H, R), map(F, T, RT).
removeAll(_, [], []).
removeAll(X, [X|R], Res) :- removeAll(X, R, Res).
removeAll(X, [H|T], [H|R]) :- H \= X, removeAll(X, T, R).
remove(_, [], []).
remove(X, [X|R], R).
remove(X, [H|T], [H|R]) :- H \= X, remove(X, T, R).
concat([], X, X).
concat([H|T], Y, [H|R]) :- concat(T, Y, R).
is_list([]).
is_list([_|_]).
is_list(_) :- fail.
reduce(_, [], _) :- fail.
reduce(_, [X], _) :- fail.
reduce(F, [A, B], R) :- call(F, A, B, R).
reduce(F, [H|T], Ret) :- reduce(F, T, R), call(F, H, R, Ret).
%% w/ init value
reduce(_, Init, [], Init).
reduce(F, Init, Array, Ret) :- reduce(F, [Init|Array], Ret).
filter(_, [], []).
filter(F, [H|T], R) :- not(call(F, H)), filter(F, T, R).
filter(F, [H|T], [H|R]) :- call(F, H), filter(F, T, R).
forEach(_, []).
forEach(F, [H|T]) :- call(F, H), forEach(F, T).
flatten([], []).
flatten([H|T], [H|R]) :- not(is_list(H)), flatten(T, R).
flatten([H|T], R) :- is_list(H), flatten(H, R1), flatten(T, R2), concat(R1, R2, R).
flatMap(_, [], []).
flatMap(F, [H|T], R) :- map(F, [H|T], Tmp), flatten(Tmp, R).
count(_, [], 0).
count(X, [X|T], R) :- count(X, T, Tmp), R is 1 + Tmp.
count(X, [H|T], R) :- H \= X, count(X, T, R).
contains(_, []) :- fail.
contains(X, [X|_]).
contains(X, [H|T]) :- H \= X, contains(X, T).
removeLast(_, [], []).
removeLast(X, [Y, X], [Y]).
removeLast(X, [H|T], [H|R]) :- removeLast(X, T, R).
reverse([], []).
reverse([H|T], R) :- reverse(T, Tr), concat(Tr, [H], R).
unique([], []).
unique([H|T], [H|R]) :- removeAll(H, T, Tmp), unique(Tmp, R).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment