[Haskell-cafe] Why is Haskell flagging this?

aditya siram aditya.siram at gmail.com
Fri Dec 17 22:32:26 CET 2010


To make that a little clearer, here is code that uses two calls to fmap to
drill through two monadic layers:
f :: [Int] -> IO [Int]
f lst = do return lst

main = do let lst = f [1,2,3,4,5]
          fmap (fmap (+1)) lst

So the order of operations is :
1. The first fmap converts an IO [Int] to [Int] and hands it off to the
second fmap
2. The second fmap applies the (+1) function to every element of the list.
3. The second fmap re-wraps the elements back into a [Int]
4. The first fmap re-wraps and returns the transformed [Int] into an IO
[Int].

-deech


On Fri, Dec 17, 2010 at 3:27 PM, aditya siram <aditya.siram at gmail.com>wrote:

> I think it is giving you the error because you the "fmap" in your code is
> operating on the IO monad and not the List monad. In order to get it to
> work, you can remove the IO layer with ">>=" as below:
>
>
> f :: [Int] -> IO [Int]
> f lst = do return lst
>
> main = do let lst = f [1,2,3,4,5]
>           lst >>= return . fmap (+1)
>
> Or you can not wrap the list in IO to begin with, my guess is that you
> wrote 'f' to make the compiler happy at some point in development:
> main = do let lst = [1,2,3,4,5]
>           return $ fmap (+1) lst
>
> -deech
>
> On Fri, Dec 17, 2010 at 11: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
>>
>> ===============================
>>
>> 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/943dbab9/attachment-0001.htm>


More information about the Haskell-Cafe mailing list