Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Seven Languages in Seven Weeks: Prolog, Day 2
fact(0, 1).
fact(N, Out) :- N > 0, N1 is N - 1, fact(N1, Prev), Out is N * Prev.
fib(1, 1).
fib(2, 1).
fib(N, Out) :- N > 2, N1 is N - 1, N2 is N - 2, fib(N1, Prev), fib(N2, PrevPrev), Out is Prev + PrevPrev.
sort(list) =
for i in [0..list.length]
list[i] <= list[i + 1]
sum([a1, a2, a3, ..., an]) = a1 + a2 + a3 + ... + an
min([Head | []], Head).
min([Head | Tail], TailMin) :- min(Tail, TailMin), TailMin =< Head.
min([Head | Tail], Head) :- min(Tail, TailMin), TailMin > Head.
reverse_list([], []).
reverse_list([Head | Tail], Out) :- reverse_list(Tail, TailReversed), append(TailReversed, [Head], Out).
sort_list([], []).
sort_list([Head], [Head]).
sort_list([First, Second | Tail], Sorted) :-
divide([First, Second | Tail], Left, Right),
sort_list(Left, LeftSorted),
sort_list(Right, RightSorted),
merge(LeftSorted, RightSorted, Sorted).
merge(LeftList, [], LeftList).
merge([], RightList, RightList).
merge([LeftHead | LeftTail], [RightHead | RightTail], [LeftHead | Merged]) :-
LeftHead =< RightHead,
merge(LeftTail, [RightHead | RightTail], Merged).
merge([LeftHead | LeftTail], [RightHead | RightTail], [RightHead | Merged]) :-
LeftHead > RightHead,
merge([LeftHead | LeftTail], RightTail, Merged).
divide([], [], []).
divide([Head], [Head], []).
divide([First, Second | Tail], [First | Left], [Second | Right]) :-
divide(Tail, Left, Right).
sort_list(Input, Output) :-
permutation(Input, Output),
check_order(Output).
check_order([]).
check_order([Head]).
check_order([First, Second | Tail]) :-
First =< Second,
check_order([Second | Tail]).
sum(0, []).
sum(Total, [Head | Tail]) :- sum(Sum, Tail), Total is Head + Sum.
@brikis98

This comment has been minimized.

Copy link
Owner Author

brikis98 commented Feb 12, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.