Learn You a Haskell discusses "Making a Monad" with the following Prob
type:
import Data.Ratio
newtype Prob a = Prob { getProb :: [(a,Rational)] } deriving Show
Prob
represents an a
type, and then a Rational
representing the probability of this a
being used.
Let's look at a Prob
instance:
*Main> Prob [('a', 1%2), ('b', 1%2)]
Prob {getProb = [('a',1 % 2),('b',1 % 2)]}
LYAH poses an exercise to figure out how to turn thisSituation
, of type Prob(Prob Char)
into Prob Char
:
thisSituation :: Prob (Prob Char)
thisSituation = Prob
[( Prob [('a', 1%2),('b',1%2)], 1%4)
,( Prob [('c', 1%2),('d',1%2)], 3%4)
]
Here's what I came up with:
flatten :: Prob (Prob a) -> Prob a
flatten pp = Prob $ convert $ getProb pp
convert :: [(Prob a, Rational)] -> [(a, Rational)]
convert xs = concat $ map f xs
f :: (Prob a, Rational) -> [(a, Rational)]
f (p, r) = map (mult r) (getProb p)
mult :: Rational -> (a, Rational) -> (a, Rational)
mult r (x, y) = (x, r*y)
I tried point-free
as so:
flatten :: Prob (Prob a) -> Prob a
flatten = Prob $ convert $ getProb
But got this error:
*Main> :l MakingMonad.hs
[1 of 1] Compiling Main ( MakingMonad.hs, interpreted )
MakingMonad.hs:37:11:
Couldn't match expected type `Prob (Prob a) -> Prob a'
with actual type `Prob a0'
In the expression: Prob $ convert $ getProb
In an equation for `flatten': flatten = Prob $ convert $ getProb
MakingMonad.hs:37:28:
Couldn't match expected type `[(Prob a0, Rational)]'
with actual type `Prob a1 -> [(a1, Rational)]'
In the second argument of `($)', namely `getProb'
In the second argument of `($)', namely `convert $ getProb'
In the expression: Prob $ convert $ getProb
Failed, modules loaded: none.
Can I make flatten
point-free? If so, please show me how. If not, please explain why.
When you use $
in flatten
, you get code that looks like
flatten = Prob $ convert $ getProb
==> Prob (convert (getProb))
Which is not what you want.
You want Prob . convert . getProb