转换为Pointfree风格?

时间:2014-08-31 15:14:28

标签: haskell pointfree

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点免费吗?如果是这样,请告诉我如何。如果没有,请解释原因。

1 个答案:

答案 0 :(得分:7)

$中使用flatten时,您会看到类似

的代码
flatten = Prob $ convert $ getProb
==> Prob (convert (getProb))

这不是你想要的。

您想要Prob . convert . getProb