I am learning Prolog, specifically GNU Prolog, for fun. I thought an interesting challenge would be to generate a sequence of Collatz numbers given a seed, which here is 5. Here's my pseudocode:
collatz(curr, next) -> if even, next is curr / 2
collatz(curr, next) -> if odd, next is curr * 3 + 1
collatz_seq(1, [1]) -> terminate and return 1
collatz_seq(curr, [curr | accum]) -> next = collatz(curr), collatz_seq(next, accum)
I translated that to Prolog like this:
collatz(Curr, Next) :-
0 is Curr mod 2,
Next is Curr / 2.
collatz(Curr, Next) :-
1 is Curr mod 2,
Next is Curr * 3 + 1.
collatz_seq(1, [1]) :- !.
collatz_seq(Curr, [Curr | Accum]) :-
collatz(Curr, Next),
collatz_seq(Next, Accum).
% collatz_seq(3, X).
I first ran my code like this: gprolog --consult-file collatz.pl and tested out 3 with collatz_seq(3, X). in the REPL. uncaught exception: error(type_error(integer,5.0),(is)/2) was the REPL's response. I think that there's a problem here with 5 being misrepresented as 5.0. For 3 as input, the sequence should go 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1, but it terminates at 5. How do I avoid this intermingling of floats and ints when a float's decimal point is just zero?