Skip to content

Instantly share code, notes, and snippets.

@draftcode
Created December 16, 2011 06:45
Show Gist options
  • Select an option

  • Save draftcode/1484841 to your computer and use it in GitHub Desktop.

Select an option

Save draftcode/1484841 to your computer and use it in GitHub Desktop.
first([X|_], X).
second([_,X|_], X).
nth(1, [X|_], X).
nth(N, [_|L], X) :-
N > 1, N1 is N-1, nth(N1, L, X).
len([], 0).
len([_|L], N) :-
len(L, N1), N is N1+1.
max_list([X], X).
max_list([X|L], M) :-
max_list(L, M1), M is max(X, M1).
rev_range(0, []).
rev_range(N, [N|L1]) :-
N > 0, N1 is N-1,
rev_range(N1, L1).
range(I, N, []) :- I > N.
range(I, N, [I|L1]) :-
I =< N, I1 is I+1,
range(I1, N, L1).
collatz(1, [1]).
collatz(N, [N|L1]) :-
N > 1, N mod 2 =:= 0, N1 is N//2, collatz(N1, L1).
collatz(N, [N|L1]) :-
N > 1, N mod 2 =:= 1, N1 is N*3+1, collatz(N1, L1).
inc_list([], []).
inc_list([X|L], [X1|L1]) :-
X1 is X+1, inc_list(L, L1).
replace([], []).
replace([X|L], [X1|L1]) :-
rule(X, X1),
replace(L, L1).
rule(i, '私').
rule(you, 'あなた').
rule(have, '持つ').
rule(love, '愛する').
rule(a, '一つの').
rule(pen, 'ペン').
rule(book, '本').
append([], Y, Y).
append([X|Xs], Y, [X|Zs]) :- append(Xs, Y, Zs).
last(L, X) :- append(_, [X], L).
memb(X, L) :- append(_, [X|_], L).
member(X, [X|_]).
member(X, [_|L]) :- member(X, L).
common([], _, []).
common([X|L], M, [X|L1]) :-
member(X, M),
!,
common(L, M, L1).
common([_|L], M, L1) :-
common(L, M, L1).
reverse([], []).
reverse([X|L], R) :-
reverse(L, R1),
append(R1, [X], R).
rev(L, R) :- rev(L, [], R).
rev([], R, R).
rev([X|L], Y, R) :- rev(L, [X|Y], R).
palindrome(L) :- reverse(L, L).
permutation([], []).
permutation(L, [X|L2]) :-
del(X, L, L1),
permutation(L1, L2).
del(X, [X|L], L).
del(X, [Y|L], [Y|L1]) :-
del(X, L, L1).
slow_sort(L, L1) :-
permutation(L, L1),
ordered(L1).
ordered([]).
ordered([_]).
ordered([X,Y|L]) :-
X =< Y,
ordered([Y|L]).
qsort([], []).
qsort([X|L], S) :-
partition(L, X, L1, L2),
qsort(L1, S1),
qsort(L2, S2),
append(S1, [X|S2], S).
partition([], _, [], []).
partition([Y|L], X, [Y|L1], L2) :-
Y < X,
partition(L, X, L1, L2).
partition([Y|L], X, L1, [Y|L2]) :-
Y >= X,
partition(L, X, L1, L2).
pos([], []).
pos([X|L1], [X|L2]) :-
X > 0,
!,
pos(L1, L2).
pos([_|L1], L2) :-
pos(L1, L2).
sum_list([], 0).
sum_list([X|L], S) :-
sum_list(L, S1),
S is X+S1.
ge_list([], _, []).
ge_list([X|Xr], Y, [X|Zs]) :-
X >= Y,
!,
ge_list(Xr, Y, Zs).
ge_list([_|Xr], Y, Zs) :-
ge_list(Xr, Y, Zs).
% vim: ft=prolog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment