I am new to Haskell and generally program. I am trying to define a function that generates a sequence of Collatz numbers from n. I have:
collatz n = (collatz' n) : 1
where collatz' n = (takeWhile (>1) (collatz'' n))
where collatz'' n = n : collatz'' (collatz''' n)
where collatz''' 1 = 1
collatz''' n = if (even n) then (div n 2) else ((3*2)+1)
When I run this in GHCi, I get an error:
No instance for (Num [t])
arising from the literal `2' at <interactive>:1:7
Possible fix: add an instance declaration for (Num [t])
I do not know what it means. It seems that the problem is adding "1" to the list. This problem arises because
collatz' n = (takeWhile (>0) (collatz'' n))
generates an infinite sequence of "1" s, following the correct sequence Collatz; However,
collatz' n = (takeWhile (>1) (collatz'' n))
generates all Collatz numbers from n except "1". What am I doing wrong?
source
share