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.
First, we define the simple auxiliary predicate
collatz_next/2
to performs a single Collatz step:To advance to a fixed point, we use the meta-predicates
fixedpoint/3
andfixedpointlist/3
: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:Assuming you want to write a
collatz_list/2
predicate with parameters(int, list)
, wherelist
is the collatz sequence starting withint
and eventually ending with1
(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:
Modified version, includes starting number
Let's test it: