[Haskell-beginners] Sequence function

David McBride toad3k at gmail.com
Tue Sep 26 18:28:48 UTC 2017


Monadic bind has this signature (Monad m => m a -> (a -> m b) -> m b.
Note that m is the same in both arguments and also the return value.

So when  you see p >>= \_ -> q ..., that means both p and q must be (m
Something), where the m is the same.

So when you go (Just 1 >>= \x -> return [] >>= \y -> return (x:y))
you know that return [] and return (x:y) are both using the Maybe
Monad instance because in Just 1, the m is Maybe.

So return [] is then equivalent to Just [], and return (x:y) is
equivalent to Just (x:y).  I hope that made sense.

On Tue, Sep 26, 2017 at 2:10 PM, Jimbo <jimbo4350 at gmail.com> wrote:
> Thank you very much. Final question, in the line:
>
> return (1 : []) -- Just [1]
>
> Does the value ([1] in this case) get wrapped in Just because of the type
> signature of sequence? I.e
>
> sequence :: Monad m => [m a] -> m [a]
>
>
>
> On 26/09/2017 1:49 PM, David McBride wrote:
>>
>> Remember that foldr has flipped operator order from foldl.
>>
>>> :t foldl
>>
>> foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b
>>>
>>> :t foldr
>>
>> foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b
>>
>> That means that you should expand them in the opposite order from how
>> it seems to read.
>>
>> p >>= \x ->  -- Just 1 >>= \ 1
>> q >>= \y -> -- return [] >>= \ []
>> return (1 : []) -- Just [1]
>>
>>
>>
>> On Tue, Sep 26, 2017 at 12:59 PM, Jimbo <jimbo4350 at gmail.com> wrote:
>>>
>>> Hello everyone,
>>>
>>> Just trying to understand the sequence function as follows:
>>>
>>> sequence [Just 1]
>>>
>>> -- evaluates to Just [1]
>>>
>>> sequence = foldr mcons (return [])
>>>      where mcons p q = p >>= \x -> q >>= \y -> return (x:y)
>>>
>>> -- I'm trying to walk through the code as follows, I understand what is
>>> below isn't
>>> -- haskell code
>>>
>>> p >>= \x ->              []
>>> q >>= \y ->        Just 1
>>> return (x:y)    --  [] : Just 1
>>>
>>> Am I thinking of sequence correctly here?
>>>
>>> Best regards,
>>>
>>> Jim
>>>
>>> _______________________________________________
>>> Beginners mailing list
>>> Beginners at haskell.org
>>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>>
>> _______________________________________________
>> Beginners mailing list
>> Beginners at haskell.org
>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners


More information about the Beginners mailing list