Help me understand this error like Haskell (GHCI): (Num [Char]) when adding a number to a string

I spent my annual attempt to learn Haskell this weekend, and, as always, when I actually try to write a recursive function (and not just type text from a tutorial), I get a type error.

I am very grateful for understanding (1) what the error means (I do not understand "fix"); and (2) why the error occurs at all - I’m sure that I’m not mistaken about the types being passed.

My code is:

tell :: (Show a) => [a] -> String  
tell'in :: (Show a, Num n) => [a] -> n -> String -> (n, String)
tell [] = "The list is empty"  
tell (x:[]) = "The list has one element: " ++ show x  
tell (x:xs) = "The list has " ++ n ++ " elements: " ++ s where (n, s) = (tell'in (xs) (1) (show x))  


tell'in (x:[]) n s = ((n + 1), (s ++ " and " ++ (show x)))
tell'in (x:xs) n s = tell'in xs (n+1)  (s ++ " and " ++ show x)

And the error I get when I try to load it into GHCI:

[1 of 1] Compiling Main             ( example.hs, interpreted )

example.hs:13:88:
    Could not deduce (Num [Char]) arising from the literal `1'
    from the context (Show a)
      bound by the type signature for tell :: Show a => [a] -> String
      at example.hs:(11,1)-(13,99)
    Possible fix:
      add (Num [Char]) to the context of
        the type signature for tell :: Show a => [a] -> String
      or add an instance declaration for (Num [Char])
    In the second argument of `tell'in', namely `(1)'
    In the expression: (tell'in (xs) (1) (show x))
    In a pattern binding: (n, s) = (tell'in (xs) (1) (show x))
Failed, modules loaded: none.
Prelude>
+3
source share
3 answers

tell'in Num n => n, (++) ing String (aka [Char]) tell. , show n n.

+3

tell'in , , . tell tell'in (1), (n) , . , , . , , ([Char]) , , 1. ,

"The list has " ++ show n ++ " elements: " ++ ...
+2

, : , !

tell'in tell :

tell :: (Show a) => [a] -> String  
tell'in :: (Show a, Num n) => [a] -> n -> String -> (n, String)

, :

tell (x:xs) = "The list has " ++ n ++ " elements: " ++ s
    where (n, s) = tell'in (xs) (1) (show x)) 

:

--   vvvvvvvvvvvvvvvvvvvvvvv                      vvvvvvvv
tell ((x:xs)::(Show a=>[a])) = "The list has " ++ (n::Int) ++ " elements: " ++ s
    where (n::Int, s::String) = tell'in (xs) (1::Int) (show x)) 
--        ^^^^^^^^^^^^^^^^^^^^               ^^^^^^^^

, .


In any case, it is recommended to use ::Intinstead ::Num n=>n, because the latter will be generalized to ::Integer, whenever the exact type is not specified. Intno more than one machine word (32/64 bit), and therefore it is faster than an arbitrary size Integer.

+1
source

All Articles