Learn You a Haskell討論「製作一個單子」具有以下Prob
類型:轉換爲Pointfree風格?
import Data.Ratio
newtype Prob a = Prob { getProb :: [(a,Rational)] } deriving Show
Prob
表示a
類型,然後被用於表示此a
的概率的Rational
。
讓我們看一個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
點,免費的嗎?如果是這樣,請告訴我如何。如果沒有,請解釋原因。
變化'$''要在.''flatten' – 2014-08-31 15:16:26