gpt4 book ai didi

haskell - 转换为 Pointfree 风格?

转载 作者:行者123 更新时间:2023-12-02 07:28:01 25 4
gpt4 key购买 nike

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 提出了一个练习来弄清楚如何将类型为 Prob(Prob Char)thisSituation 转换为 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中使用$时,你得到的代码看起来像

flatten = Prob $ convert $ getProb
==> Prob (convert (getProb))

这不是你想要的。

你想要 Prob 。转变 。获取概率

关于haskell - 转换为 Pointfree 风格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25593318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com