我有这个功能
rulesApply :: [PhrasePair] -> Phrase -> Phrase
rulesApply pp = try (transformationsApply "*" reflect pp )我想学习如何让它变得无关紧要。
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但这会导致编译错误。
发布于 2013-11-16 04:14:40
无论何时你有一些看起来像
\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发布于 2013-11-16 04:16:26
删除这些点相对容易,但您应该一步一步地移动。
rulesApply pp = try ( transformationsApply "*" reflect pp)
=== [partial application]
rulesApply pp = try ((transformationsApply "*" reflect) pp)
=== [definition of (.)]
rulesApply pp = (try . transformationsApply "*" reflect) pp
=== [eta reduction]
rulesApply = try . transformationsApply "*" reflect发布于 2013-11-16 03:45:32
实际上,这很简单:
rulesApply :: [PhrasePair] -> Phrase -> Phrase
rulesApply = try . transformationsApply "*" reflect无指针编程不仅仅关乎美学。这是关于在更高的层次上处理问题:不是对函数的变量进行操作,而是对函数本身进行操作,从而消除了整个问题领域。
让我们分析一下(.)操作符的签名。
(.) :: (b -> c) -> (a -> b) -> (a -> c)我有意用大括号将a -> c括起来,以表明需要两个函数才能生成另一个函数。在这方面,它与原始值上的任何运算符没有太大区别,例如:
(+) :: Int -> Int -> Int现在,不要着迷于它,也不要期望它会在你的道路上遇到任何问题。这只是你口袋里的另一个工具,应该适当地使用。它最常见的用法是避免多余的lambda。下面是一些示例:
putStrLn . (++ "!") == \a -> putStrLn (a ++ "!")
void . return == \a -> return a >> return ()第二个示例基本上等同于const (return ()) == \a -> return (),但出于美学原因,我更喜欢它。我认为,编译器无论如何都会优化这些东西。
https://stackoverflow.com/questions/20009293
复制相似问题