[Haskell-beginners] Need better explanation of the 'flipThree' example in LYAH

Olumide 50295 at web.de
Wed Sep 19 10:03:04 UTC 2018


Thanks Francesco. You are right. I had one too many rbraces.

However from the definition

fmap f (Prob xs) = Prob $ map (\(x,p) -> (f x , p))  xs

and  x = Head | Tails suggests to me that f ought to be a function like 
any (==Heads) that applies to [x]

Therefore I've changed the desugared expression to

flatten( fmap (\a -> flatten( fmap ( \b -> return ( any (== Heads) [a,b] 
) ) coin ) ) coin )

So that from the definition of coin, the inner expression

fmap ( \b -> return ( any (== Heads) [a,b] ) ) coin

expands to

fmap ( \b -> return ( any (== Heads) [a,b] ) ) Prob[ (Heads, 1%2) , 
(Tails, 1%2) ]

Detour: writing all this made me realize that (1) the lambda is applied 
the lambda to all elements(?) of the Prob, and (2) the term a represents 
each element of the outer Prob.

So that the above expression becomes

Prob $ [ (any (==Heads)[a,Head], 1%2) , (any (==Head)[a,Tails], 1%2) ]

writing all this made me realize that (1) the lambda is applied to all 
elements(?) of the Prob, and that (2) the term a represents each element 
of the outer Prob -- I think I am starting to see the 
similarity/connection between the do-notation and list comprehensions.

Returning to the above expression, when the term a is Heads, we get

Prob [ (return any (==Heads)[Heads,Head], 1%2) , (return any 
(==Head)[Heads,Tails], 1%2) ]

and because

return any (==Heads)[Heads,Head]  = Prob[True,1%1] , and
return any (==Heads)[Heads,Tails] = Prob[True,1%1]

The above expression becomes

Prob [ (Prob[True,1%1] , 1%2 ) , ( Prob[True,1%1] , 1%2 ) ]

The double Prob makes it clear why flatten is needed.

I'll stop here and wait for your feedback.

BTW, I'm considering using GHC.Proof to assert that this sequence of 
reductions is equivalent.

Regards,

- Oumide


On 17/09/18 01:09, Francesco Ariis wrote:
> Hello Olumide,
> 
> On Mon, Sep 17, 2018 at 12:15:58AM +0100, Sola Aina wrote:
>> flatten( fmap (\a -> ( flatten( fmap ( \b -> return [a,b] ) coin ) ) coin )
>>
>> Is this how to proceed and how am I to simplify this expression?
> 
> I get a slightly different final expression:
> 
>      flatten (fmap (\a -> flatten (fmap (\b -> return [a,b]) coin)) coin)
>      -- notice the lack of `(` before the second `flatten`
> 
> This could be rewritten as:
> 
>      flatMap (\a -> flatMap (\b -> return [a,b]) coin) coin
> 
>      -- flatMap :: (a1 -> Prob a2) -> Prob a1 -> Prob a2
>      -- flatMap f x = flatten (fmap f x)
> 
> which is a bit easier on the eyes. This expression cannot be simplified
> any further if we don't bring to the table the definition of `coin`!
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
> 


More information about the Beginners mailing list