"No instance for (Num [t])" error in Collatz function

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?

+3
source share
3 answers
, Haskell, , . : pre , somelist : 7 , ap . (collatz' n) : 1 , (collatz' n) - .

: 1 ++ [1].

+5

(:) :: a -> [a] -> [a]
collatz n = (collatz' n) : 1 1 [a].
, - (collatz' n) ++ [1]
if (even n) then (div n 2) else ((3*2)+1) ((3*n)+1 - , collatz''' 7 = 7

+6

Data.Sequence . "snoc" ( ), "" ( ).

span takeUntil.

: span p xs , (takeWhile p xs, dropWhile p xs) p xs, , , splitAt n xs (take n xs, drop n xs).

, span, takeUntil:

takeUntil p xs = taken ++ take 1 dropped where
                 (taken, dropped) = span p xs

, , collatz n = (collatz' n) : 1.

, .

0

Source: https://habr.com/ru/post/1752770/


All Articles