Last active
February 17, 2025 19:08
-
-
Save dc0d/2baff058d326758826494fafdd32b8e5 to your computer and use it in GitHub Desktop.
P-99: Ninety-Nine Prolog Problems
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% This is Prolog. This is not Perl. | |
:- module(p99, []). | |
% source: | |
% https://www.ic.unicamp.br/~meidanis/courses/mc336/2009s2/prolog/problemas/ | |
% P01 | |
last_of([X], X). | |
last_of([_|Rest], R) :- | |
last_of(Rest, R). | |
% P03 | |
kth_of([E|_], N, N, Out) :- Out = E. | |
kth_of([_|T], N, Current, Out) :- | |
Current<N, | |
C1 is Current+1, | |
kth_of(T, N, C1, Out). | |
% P04 | |
len_of([], Out) :- Out = 0. | |
len_of([_|T], Out) :- | |
len_of(T, L1), | |
Out is 1+L1. | |
% P05 | |
rev_of([], Out) :- Out = []. | |
rev_of([H|T], Out) :- | |
rev_of(T, R1), | |
append(R1, [H], Out). | |
% P06 | |
is_palindrome(L, Out) :- | |
rev_of(L, L1), | |
(L1 = L -> Out=true ; Out=false). | |
% P07 | |
flatten_of([], Out) :- Out = []. | |
flatten_of([H|T], Out) :- | |
( | |
is_list(H) -> | |
flatten_of(H, L1), | |
flatten_of(T, L2), | |
append(L1, L2, Out) | |
; | |
flatten_of(T, L), | |
append([H], L, Out) | |
). | |
% P08 | |
no_duplicates([], []). | |
no_duplicates([E], Out) :- !, Out=[E]. | |
no_duplicates([H,H|T], Out) :- !, no_duplicates([H|T], Out). | |
no_duplicates([H|T], [H|L1]) :- no_duplicates(T, L1). | |
:- begin_tests(test_suite). | |
test(last_of, all(Out = [d])) :- | |
last_of([a,b,c,d], Out). | |
test(kth_of, all(Out = [c])) :- | |
kth_of([a,b,c,d],3,1,Out). | |
test(len_of) :- | |
len_of([a,b,c,d], 4), | |
len_of([a,b,c], 3), | |
len_of([], 0). | |
test(rev_of) :- | |
rev_of([a,b,c], [c,b,a]), | |
rev_of([a,b,c,d], [d,c,b,a]). | |
test(is_palindrome) :- | |
is_palindrome([a,b,c,b,a], true). | |
test(is_palindrome) :- | |
is_palindrome([a,b,d,d,d,a], false). | |
test(flatten_of) :- | |
flatten_of([1,[2,3]], [1,2,3]), | |
flatten_of([[1],[2,3]], [1,2,3]), | |
flatten_of([[1],[2],[3]], [1,2,3]), | |
flatten_of([[1,2],[3]], [1,2,3]), | |
flatten_of([[1,2],3], [1,2,3]). | |
:- end_tests(test_suite). | |
:- begin_tests(no_duplicates). | |
test(1) :- | |
no_duplicates([], []). | |
test(2) :- | |
no_duplicates([1], [1]). | |
test(3) :- | |
no_duplicates([1,2], [1,2]). | |
test(4) :- | |
no_duplicates([1,1,1,2,2,2], [1,2]). | |
test(5) :- | |
no_duplicates([a,a,a,a,b,c,c,a,a,d,e,e,e,e], [a,b,c,a,d,e]). | |
:- end_tests(no_duplicates). | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment