Haskell No instance for (Num ()) arising from the literal

haskell

Solution

This is because GHCi tries to choose a type signature for your function more strictly than GHC will. It is often the case that you don't want to have to write out in-line type signatures in GHCi, so it attempts to choose a default that will execute. If you ask GHCi what it chose for `addString`, you get

> :type addString
addString :: () -> [String] -> [String]

As you can see, GHCi has incorrectly assumed the wrong type signature. You can fix this by adding it to the definition:

> let addString :: Show a => a -> [String] -> [String]; addString = ((:) . show)
> addString 1 []
["1"]

This is a known and annoying consequence of having it work correctly in so many other cases. There's a lot of types that GHCi just "gets" that you would have to give a signature for when compiling it in a file, but there are some that it just messes up for whatever reason.

Problem

Why `addString` invocation is different than inlined expression? ``` Prelude> ((:).show) 1 [] ["1"] Prelude> let addString = ((:).show) Prelude> addString 1 [] <interactive>:99:11: No instance for (Num ()) arising from the literal `1' Possible fix: add an instance declaration for (Num ()) In the first argument of `addString', namely `1' In the expression: addString 1 [] In an equation for `it': it = addString 1 [] ```

Original source