Learn You a Haskell使用以下Prob
类型讨论“制作Monad”:
import Data.Ratio
newtype Prob a = Prob { getProb :: [(a,Rational)] } deriving Show
Prob
表示a
类型,然后表示Rational
表示使用此a
的概率。
让我们看一下Prob
实例:
*Main> Prob [('a', 1%2), ('b', 1%2)]
Prob {getProb = [('a',1 % 2),('b',1 % 2)]}
LYAH提出了一个练习,以确定如何将thisSituation
Prob(Prob Char)
转换为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)
]
以下是我提出的建议:
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)
我尝试了point-free
:
flatten :: Prob (Prob a) -> Prob a
flatten = Prob $ convert $ getProb
但得到了这个错误:
*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.
我可以让flatten
点免费吗?如果是这样,请告诉我如何。如果没有,请解释原因。
答案 0 :(得分:7)
在$
中使用flatten
时,您会看到类似
flatten = Prob $ convert $ getProb
==> Prob (convert (getProb))
这不是你想要的。
您想要Prob . convert . getProb