gpt4 book ai didi

haskell - Haskell 中的 Pointfree 风格编程

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

我有这个功能

rulesApply :: [PhrasePair] -> Phrase ->  Phrase

rulesApply pp = try (transformationsApply "*" reflect pp )

我想学习如何让它成为 pointfree。

try :: (a -> Maybe a) -> a -> a
try f x = maybe x id (f x)
transformationsApply :: Eq a => a -> ([a] -> [a]) -> ([([a], [a])] -> ([a] -> Maybe [a]))
transformationsApply wc f pfPair list = foldr1 orElse (map (transformationApply wc f list) pfPair)


rulesApply pp = try (transformationsApply "*" reflect pp )

(transformationsApply "*"reflect ) pp 具有类型 Eq a => ([([a], [a])] -> ([a] -> Maybe [a ]))

我们看到了

try :: (a -> Maybe a) -> a -> a

所以 try 将函数 (a -> Maybe a) 作为参数。我们看到 (transformationsApply "*"reflect ) pp 的返回类型是 ([a] -> Maybe [a])) 所以我们应该可以写。

rulesApply pp = try . (transformationsApply "*" reflect) pp

但这会导致编译错误。

最佳答案

当你有类似的东西时

\x -> f (g x)

你可以把它变成

f . g

在这种情况下,你有

s          x  = f   (g                                 x  )
rulesApply pp = try (transformationsApply "*" reflect pp )

可以将其转换(通过将参数移到等式的另一边)

s          = \x  -> f   (g                                 x  )
rulesApply = \pp -> try (transformationsApply "*" reflect pp )

反过来,根据我们的规则,

s          = f   . g
rulesApply = try . transformationsApply "*" reflect

关于haskell - Haskell 中的 Pointfree 风格编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20009293/

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