带有多个函数参数的点自由表示法

时间:2013-10-31 06:13:32

标签: pointfree elm

我正在尝试移植以下Haskell代码(http://codepad.org/MMydRCxo

foo :: Int -> Int -> Int -> Maybe Bool
foo a b c = if a == 1 then Just True else Nothing

bar :: Int -> Int -> Bool
bar b c = maybe False id $ foo 1 b c

-- point free
bar' :: Int -> Int -> Bool
bar' = ((maybe False id $) .) . foo 1

main = do
  print $ bar 2 3
  print $ bar' 2 3
到榆树,但还没有运气。 (http://share-elm.com/sprout/5271f160e4b03cf6e675bc97

foo : Int -> Int -> Int -> Maybe Bool
foo a b c = if a == 1 then Just True else Nothing

bar : Int -> Int -> Bool
bar b c = maybe False id <| foo 1 b c

-- point free
bar' : Int -> Int -> Bool
bar' = ((maybe False id <|) .) . foo 1

main = flow down [
    asText <| bar 2 3
  , asText <| bar' 2 3]

任何想法,如果有可能让这项工作在榆树免费? :)

DOBI

2 个答案:

答案 0 :(得分:4)

您可以尝试删除<|并使用前缀表示法中的合成功能。 它首先会创建一个带参数的函数,并使 函数组成foo 1

这样,调用bar' 2将返回采用最后一个参数的组合函数。 即(http://share-elm.com/sprout/52720bc5e4b03cf6e675bcc8):

foo : Int -> Int -> Int -> Maybe Bool
foo a b c = if a == 1 then Just True else Nothing

bar : Int -> Int -> Bool
bar b c = maybe False id <| foo 1 b c

bar' : Int -> Int -> Bool
bar' = (.) (maybe False id) . foo 1
-- the explicit evaluation precedence being: ((.) (maybe False id)) . (foo 1)

main = flow down [
    asText <| bar 2 3
  , asText <| bar' 2 3]

答案 1 :(得分:2)

在Haskell中,以下表达式都是等价的:

(f .) . g
(.) f . g
(.) ((.) f) g
((.).(.)) f g
(\x y -> f (g x y))

这意味着f是一元函数,g是二元函数,2个参数传递给g,其结果传递给f。阅读有关“owl” operator的更多信息,了解其工作原理。

因此,如果您想将类似的表达式转换为Elm,则可以使用以下方法之一:

(.:) = (<<)<<(<<) -- owl operator definition
(<<) f << g
(<<) ((<<) f) g
f .: g

例如:

((<<) negate << (+)) 3 4 -- returns -7
(negate .: (+)) 3 4      -- returns -7

注意:Elm 0.13 (.)替换为(<<),而(>>)现在与flip (<<) 相同

相关问题