[Haskell-cafe] Why is Haskell flagging this?

David Leimbach leimy2k at gmail.com
Fri Dec 17 22:56:37 CET 2010


On Fri, Dec 17, 2010 at 9:04 AM, michael rice <nowgate at yahoo.com> wrote:

> I don't understand this error message. Haskell appears not to understand
> that 1 is a Num.
>
> Prelude> :t 1
> 1 :: (Num t) => t
> Prelude> :t [1,2,3,4,5]
> [1,2,3,4,5] :: (Num t) => [t]
> Prelude>
>
> Michael
>
> ===================
>
> f :: [Int] -> IO [Int]
> f lst = do return lst
>
> main = do let lst = f [1,2,3,4,5]
>           fmap (+1) lst


f takes [Int] and returns IO [Int]

fmap is

fmap :: (Functor f) => (a -> b) -> f a -> f b

That is it takes a function of a's to b's, a functor of a, and returns you a
functor of b.

So when you fmap (+1) to an IO [Int], it's trying to add 1 to a [Int], and
[Int] is not an instance of Num, so the + does not work.

Luckily you can use function composition here

(fmap . fmap) (+1) $ f [1..10]
[2,3,4,5,6,7,8,9,10,11]

fmap . fmap is the type I think you wanted:

Prelude> :t fmap . fmap
fmap . fmap
  :: (Functor f, Functor f1) => (a -> b) -> f (f1 a) -> f (f1 b)


With IO as the f Functor, and [] as the f1 Functor.


>
>
> ===============================
>
> Prelude> :l test
> [1 of 1] Compiling Main             ( test.hs, interpreted )
>
> test.hs:5:17:
>     No instance for (Num [Int])
>       arising from the literal `1' at test.hs:5:17
>     Possible fix: add an instance declaration for (Num [Int])
>     In the second argument of `(+)', namely `1'
>     In the first argument of `fmap', namely `(+ 1)'
>     In the expression: fmap (+ 1) lst
> Failed, modules loaded: none.
> Prelude>
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20101217/2d04c4d3/attachment.htm>


More information about the Haskell-Cafe mailing list