I am trying to create a function called collatz_list in Prolog. This function takes two arguments, the first one is a number and the second in a list. This list will be my output of this function. So, here's my function:
collatz_list(1,[1]).
collatz_list(N,[H|T]) :-
N > 1,
N mod 2 =:= 0,
collatz_list(N, [H|T]).
collatz_list(N,[H|T]) :-
N > 1,
N mod 2 =:= 1,
N is N*3 +1,
collatz_list(N,[H|T]).
I am struggling with creating the output list. Can anyone help me on that?
Thanks.
Assuming you want to write a collatz_list/2 predicate with parameters (int, list), where list is the collatz sequence starting with int and eventually ending with 1 (we hope so! It's an open problem so far); you just have to code the recursive definition in the declarative way.
Here's my attempt:
/* if N = 1, we just stop */
collatz_list(1, []).
/* case 1: N even
we place N / 2 in the head of the list
the tail is the collatz sequence starting from N / 2 */
collatz_list(N, [H|T]) :-
0 is N mod 2,
H is N / 2,
collatz_list(H, T), !.
/* case 2: N is odd
we place 3N + 1 in the head of the list
the tail is the collatz sequence starting from 3N + 1 */
collatz_list(N, [H|T]) :-
H is 3 * N + 1,
collatz_list(H, T).
Modified version, includes starting number
Let's test it:
full_list(N, [N|T]) :-
collatz_list(N, T).
collatz_list(1, []).
collatz_list(N, [H|T]) :-
0 is N mod 2,
H is N / 2,
collatz_list(H, T), !.
collatz_list(N, [H|T]) :-
H is 3 * N + 1,
collatz_list(H, T).
?- full_list(27, L).
L = [27, 82, 41, 124, 62, 31, 94, 47, 142|...].
First, we define the simple auxiliary predicate collatz_next/2 to performs a single Collatz step:
collatz_next(X,Y) :-
X >= 1,
( X =:= 1 -> Y = 1
; X mod 2 =:= 0 -> Y is X // 2
; Y is 3*X + 1
).
To advance to a fixed point,
we use the meta-predicates fixedpoint/3 and fixedpointlist/3:
?- fixedpoint(collatz_next,11,X).
X = 1. % succeeds deterministically
?- fixedpointlist(collatz_next,11,Xs).
Xs = [11,34,17,52,26,13,40,20,10,5,16,8,4,2,1]. % succeeds deterministically
Both meta-predicates used in above query are based on the monotone control construct if_/3 and the reified term equality predicate (=)/3, and can be defined as follows:
:- meta_predicate fixedpoint(2,?,?).
fixedpoint(P_2, X0,X) :-
call(P_2, X0,X1),
if_(X0=X1, X=X0, fixedpoint(P_2, X1,X)).
:- meta_predicate fixedpointlist(2,?,?).
fixedpointlist(P_2,X0,[X0|Xs]) :-
call(P_2, X0,X1),
if_(X0=X1, Xs=[], fixedpointlist(P_2,X1,Xs)).
Related
I am studying prolog and I am faced with a problem that I cannot deal with.
Given a number, I have to check if the sum of the factorial of each digit that composes it is equal to the number itself.
Example:
145
1! + 4! + 5! = 1 + 24 + 120
Now my problem is just how to decompose the number so that I can factorial and sum each digit.
EDIT1.
thank to #slago I understand how decompose the number, but now I have a problem to sum the factorial terms:
fact(N):-
fact(N, N, _ListNumber).
fact(N, 0, ListNumber):-
factorial(ListNumber, 1, Sum),
Sum == N.
fact(N, Number, [D|R]):-
D is Number mod 10,
Number1 is Number div 10,
fact(N, Number1, R).
factorial([], Counter, Counter).
factorial([D|R], Counter, Sum):-
print([D|R]),
checksum(D, Counter),
factorial(R, Counter, Sum).
checksum(D, Counter):-
Counter1 is Counter * D,
M is D - 1,
M >= 2, !,
checksum(M, Counter1).
I have tried like this, but I noticed [D|R] results empty, and I don't understand why.
Your code is organized in a very confusing way. It is best to code independent predicates (for more specific purposes) and, after that, use them together to get the answer you want.
Start by creating a predicate to decompose a natural number into digits.
decompose(N, [N]) :- N<10, !.
decompose(N, [D|R]) :- N>=10, D is N mod 10, M is N//10, decompose(M, R).
Example of decomposition:
?- decompose(145, D).
D = [5, 4, 1].
Then, create a predicate to compute the factorial of a natural number.
fact(N, F) :- fact(N, 1, F).
fact(0, A, A) :- !.
fact(N, A, F) :- N>0, M is N-1, B is N*A, fact(M, B, F).
Example of factorial:
?- fact(5, F).
F = 120.
After that, create a predicate to map each number of a list into its corresponding factorial (alternatively, you could use the predefined predicate maplist/3).
map_fact([], []).
map_fact([X|Xs], [Y|Ys]) :- fact(X,Y), map_fact(Xs, Ys).
Example of mapping:
?- decompose(145, D), map_fact(D, F).
D = [5, 4, 1],
F = [120, 24, 1].
You must also create a predicate to compute the sum of the items of a list (alternatively, you could use the predefined predicate sum_list/2).
sum(L, S) :- sum(L, 0, S).
sum([], A, A).
sum([X|Xs], A, S) :- B is A+X, sum(Xs, B, S).
Example of summation:
?- decompose(145, D), map_fact(D, F), sum(F, S).
D = [5, 4, 1],
F = [120, 24, 1],
S = 145.
Finally, create the predicate to check the desired number property.
check(N) :- decompose(N, D), map_fact(D, F), sum(F, N).
Example:
?- check(145).
true.
?- check(146).
false.
Goldbach’s Conjecture : Every positive even number greater than 2 is the sum of two prime numbers. Eg 28 (5,23 and 11,17)
I want Prolog code to print below (all combinations) :
?- goldbach(28, L).
Output :
L = [5,23];
L = [11, 17];
I have a code which prints single combination[5,23], but not the next [11,17].
is_prime(2).
is_prime(3).
is_prime(P) :- integer(P), P > 3, P mod 2 =\= 0, \+ has_factor(P,3).
has_factor(N,L) :- N mod L =:= 0.
has_factor(N,L) :- L * L < N, L2 is L + 2, has_factor(N,L2).
goldbach(4,[2,2]) :- !.
goldbach(N,L) :- N mod 2 =:= 0, N > 4, goldbach(N,L,3).
goldbach(N,[P,Q],P) :- Q is N - P, is_prime(Q), !.
goldbach(N,L,P) :- P < N, next_prime(P,P1), goldbach(N,L,P1).
next_prime(P,P1) :- P1 is P + 2, is_prime(P1), !.
next_prime(P,P1) :- P2 is P + 2, next_prime(P2,P1).
Drop the cuts (and add a condition to avoid duplicate answers).
goldbach(4,[2,2]).
goldbach(N,L) :-
N mod 2 =:= 0,
N > 4,
goldbach(N,L,3).
goldbach(N,[P,Q],P) :-
Q is N - P,
is_prime(Q), P < Q.
goldbach(N,L,P) :-
P < N,
next_prime(P,P1),
goldbach(N,L,P1).
The problem is about adding the multiples of the possible factorizations in the number that is input by the user.
I tried this code.
sum_factors(N,Fs) :-
integer(N) ,
N > 0 ,
setof(F , factor(N,F) , Fs ).
factor(N,F) :-
L is floor(sqrt(N)),
between(1,L,X),
( F = X ; F is N // X),
write(F), write('x'), write(X), write('='),
write(N), nl.
output of my code if i input 24:
1x1=24
24x1=24
2x2=24
12x2=24
3x3=24
8x3=24
4x4=24
6x4=24
Fs = [1, 2, 3, 4, 6, 8, 12, 24].
the correct output if i input 24 should be:
24 = 2x2x2x3
24 = 2x3x4
24 = 2x2x6
24 = 4x6
24 = 3x8
24 = 2x12
24 = 24
Can somebody explain this code line by line for me, and if possible, tell what's i'm missing from the code.
Try this solution, I think now is complete.
% The first ten prime numbers
% You may want include more, use this URL http://primes.utm.edu/lists/small/1000.txt
prime_numbers([2,3,5,7,11,13,17,19,23,29]).
% Find the lower number in a list of numbers that divide a number N
% We asume that the list of numbers is sorted in ascendent order
lower_splitter(N, [H|_], H):- N mod H =:= 0, !.
lower_splitter(N, [_|T], H):- lower_splitter(N, T, H).
% Find factors
factors(1, []):- !.
factors(N, [R|L]):- prime_numbers(P), lower_splitter(N, P, R), N1 is N div R, factors(N1, L).
% Verify is a list contains a subset
sub_set([], []).
sub_set([X|L1], [X|L2]):- sub_set(L1, L2).
sub_set([_|L1], L2):- sub_set(L1, L2).
% Find all subset in the list X.
combinations(X, R):- setof(L, X^sub_set(X, L), R).
% Auxilary predicates
list([]).
list([_|_]).
lt(X,Y):-var(X);var(Y).
lt(X,Y):-nonvar(X),nonvar(Y),X<Y.
difference([],_,[]).
difference(S,[],S):-S\=[].
difference([X|TX],[X|TY],TZ):-
difference(TX,TY,TZ).
difference([X|TX],[Y|TY],[X|TZ]):-
lt(X,Y),
difference(TX,[Y|TY],TZ).
difference([X|TX],[Y|TY],TZ):-
lt(Y,X),
difference([X|TX],TY,TZ).
%Multiply members of a list
multiply([X], X):-!.
multiply([H|T], X):-multiply(T, M), X is M *H.
start(N):- factors(N, L),
setof(R, L^S^T^D^M^(sub_set(L, S),
length(S, T),
T>1,difference(L, S, D),
multiply(S,M),
append(D,[M], R)), F), writeall(N,[L|F]).
writeall(_,[]).
writeall(N,[H|T]):- write(N),write('='),writelist(H),nl, writeall(N,T).
writelist([X]):- write(X).
writelist([X,Y|T]):- write(X),write(x), writelist([Y|T]).
Consult using the start predicate, like this:
?- start(24).
24=2x2x2x3
24=2x2x6
24=2x3x4
24=2x12
24=3x8
24=24
I'm kinda new to Prolog so I have a few problems with a certain task. The task is to write a tail recursive predicate count_elems(List,N,Count) condition List_Element > N, Count1 is Count+1.
My approach:
count_elems( L, N, Count ) :-
count_elems(L,N,0).
count_elems( [H|T], N, Count ) :-
H > N ,
Count1 is Count+1 ,
count_elems(T,N,Count1).
count_elems( [H|T], N, Count ) :-
count_elems(T,N,Count).
Error-Msg:
ERROR: toplevel: Undefined procedure: count_elems/3 (DWIM could not correct goal)
I'm not quite sure where the problem is. thx for any help :)
If you want to make a tail-recursive version of your code, you need (as CapelliC points out) an extra parameter to act as an accumulator. You can see the issue in your first clause:
count_elems(L, N, Count) :- count_elems(L,N,0).
Here, Count is a singleton variable, not instantiated anywhere. Your recursive call to count_elems starts count at 0, but there's no longer a variable to be instantiated with the total. So, you need:
count_elems(L, N, Count) :-
count_elems(L, N, 0, Count).
Then declare the count_elem/4 clauses:
count_elems([H|T], N, Acc, Count) :-
H > N, % count this element if it's > N
Acc1 is Acc + 1, % increment the accumulator
count_elems(T, N, Acc1, Count). % check the rest of the list
count_elems([H|T], N, Acc, Count) :-
H =< N, % don't count this element if it's <= N
count_elems(T, N, Acc, Count). % check rest of list (w/out incrementing acc)
count_elems([], _, Count, Count). % At the end, instantiate total with accumulator
You can also use an "if-else" structure for count_elems/4:
count_elems([H|T], N, Acc, Count) :-
(H > N
-> Acc1 is Acc + 1
; Acc1 = Acc
),
count_elems(T, N, Acc1, Count).
count_elems([], _, Count, Count).
Also as CapelliC pointed out, your stated error message is probably due to not reading in your prolog source file.
Preserve logical-purity with clpfd!
Here's how:
:- use_module(library(clpfd)).
count_elems([],_,0).
count_elems([X|Xs],Z,Count) :-
X #=< Z,
count_elems(Xs,Z,Count).
count_elems([X|Xs],Z,Count) :-
X #> Z,
Count #= Count0 + 1,
count_elems(Xs,Z,Count0).
Let's have a look at how versatile count_elems/3 is:
?- count_elems([1,2,3,4,5,4,3,2],2,Count).
Count = 5 ; % leaves useless choicepoint behind
false.
?- count_elems([1,2,3,4,5,4,3,2],X,3).
X = 3 ;
false.
?- count_elems([1,2,3,4,5,4,3,2],X,Count).
Count = 0, X in 5..sup ;
Count = 1, X = 4 ;
Count = 3, X = Count ;
Count = 5, X = 2 ;
Count = 7, X = 1 ;
Count = 8, X in inf..0 .
Edit 2015-05-05
We could also use meta-predicate
tcount/3, in combination with a reified version of (#<)/2:
#<(X,Y,Truth) :- integer(X), integer(Y), !, ( X<Y -> Truth=true ; Truth=false ).
#<(X,Y,true) :- X #< Y.
#<(X,Y,false) :- X #>= Y.
Let's run above queries again!
?- tcount(#<(2),[1,2,3,4,5,4,3,2],Count).
Count = 5. % succeeds deterministically
?- tcount(#<(X),[1,2,3,4,5,4,3,2],3).
X = 3 ;
false.
?- tcount(#<(X),[1,2,3,4,5,4,3,2],Count).
Count = 8, X in inf..0 ;
Count = 7, X = 1 ;
Count = 5, X = 2 ;
Count = 3, X = Count ;
Count = 1, X = 4 ;
Count = 0, X in 5..sup .
A note regarding efficiency:
count_elems([1,2,3,4,5,4,3,2],2,Count) left a useless choicepoint behind.
tcount(#<(2),[1,2,3,4,5,4,3,2],Count) succeeded deterministically.
Seems you didn't consult your source file.
When you will fix this (you could save these rules in a file count_elems.pl, then issue a ?- consult(count_elems).), you'll face the actual problem that Count it's a singleton in first rule, indicating that you must pass the counter down to actual tail recursive clauses, and unify it with the accumulator (the Count that gets updated to Count1) when the list' visit is done.
You'll end with 3 count_elems/4 clauses. Don't forget the base case:
count_elems([],_,C,C).
I have a problem with the recursive function of Prolog. I believe I am not implementing it right and need help.
I need to generate the first N prime numbers and return it in a list. Generating the prime number is not an issue, but rather, generating it in a list is the issue I have.
This is the part of the relevant code:
genList(_, 0, _).
genList(X, N, PrimeList, PrimeList):-
N > 0,
isprime(X),
X1 is X +1,
N1 is N -1,
genList(X1,N1,[X|PrimeList], [X|PrimeList]),!.
genList(X, N, PrimeList, PrimeList):-
N>0,
\+isprime(X),
X1 is X + 1,
genList(X1,N,PrimeList, PrimeList).
This is what I type into the Prolog interpreter:
genList(1,N, [],L).
For the 1st line, how do I make the base case such that when N=0, I stop recursing? Is this correct?
As for the next 2 clauses, I am having difficulty in thinking in terms of logic programming. I definitely feel that this is not logic programming style.
I want to say that when isPrime(X) fails, we continue to the next number without saving anything, but when isPrime(X) is true, then we recurse and continue to the next number, saving X.
How do I do that in Prolog?
First of all, you shouldn't need 4 arguments to your main predicate if you only want two. Here you want the list of the first primes up to N. So an argument for N and an argument for the list should be enough:
primeList(N, L) :-
% eventually in the body a call to a worker predicate with more arguments
Now here, your logic is explained in those terms:
primeList(N, [N|L]) :-
% If we're not at the base case yet
N > 0,
% If N is a prime
isPrime(N),
NewN is N - 1,
% Let's recurse and unifie N as the head of our result list in the head
% of the predicate
primeList(NewN, L).
primeList(N, L) :-
% Same as above but no further unification in the head this time.
N > 0,
% Because N isn't a prime
\+ isPrime(N),
NewN is N - 1,
primeList(NewN, L).
To that you'd have to add the base case
primeList(0, []).
You could rewrite that with cuts as follows:
primeList(0, []) :- !.
primeList(N, [N|L]) :-
isPrime(N),
!,
NewN is N - 1,
primeList(NewN, L).
primeList(N, L) :-
NewN is N - 1,
primeList(NewN, L).
Here's what you meant to write:
genList(N, L) :- genList(2, N, L, []).
genList(X, N, L, Z):- % L-Z is the result: primes list of length N
N > 0 ->
( isprime(X) -> L=[X|T], N1 is N-1 ; L=T, N1 is N ),
X1 is X + 1,
genList(X1,N1,T,Z)
;
L = Z.
The if-then-else construct embodies the cuts. And you're right, it's essentially a functional programming style.
We can introduce a little twist to it, disallowing requests for 0 primes (there's no point to it anyway), so that we also get back the last generated prime:
genList(1, [2], 2) :- !.
genList(N, [2|L], PN) :- N>1, L=[3|_], N2 is N-2, gen_list(N2, L, [PN]).
gen_list(N, L, Z) :- L=[P|_], X is P+2, gen_list(X, N, L, Z).
gen_list(X, N, L, Z) :- % get N more odd primes into L's tail
N > 0 ->
( isprime(X) -> L=[_|T], T=[X|_], N1 is N-1 ; L=T, N1 is N ),
X1 is X + 2,
gen_list(X1,N1,T,Z)
;
L = Z. % primes list's last node
Run it:
?- genList(8,L,P).
L = [2, 3, 5, 7, 11, 13, 17, 19]
P = 19
This also enables us to stop and continue the primes generation from the point where we stopped, instead of starting over from the beginning:
?- L = [3|_], gen_list(8, L, Z), Z=[P10|_], writeln([2|L]),
gen_list(10, Z, Z2), Z2=[P20], writeln(Z).
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29|_G1037]
[29,31,37,41,43,47,53,59,61,67,71]
P10 = 29
P20 = 71