【问题标题】:Pointfree function for fold left operation左折叠操作的无点函数
【发布时间】:2015-11-28 08:22:18
【问题描述】:

我有这个函数可以从元组中提取第四个元素,它恰好是一个整数:

fourth :: (a, b, c, Int) -> Int
fourth (a, b, c, d) = d

我想对元组列表的所有第四个整数求和。我可以通过将(+) 与(+) 组合成合适的foldr 运算符,在折叠右操作中使用fourth:

summerRight :: (a, b, c, Int) -> Int -> Int
summerRight tuple n = fourth tuple + n

整个事情都可以写成无意义的:

summerRight = (+) . fourth

现在,如果我想将总和表示为向左折叠,我需要一个运算符:

summerLeft :: Int -> (a, b, c, Int) -> Int
summerLeft n tuple = n + fourth tuple

我无法编写最后一个无点函数。

可以写summerLeftpointfree吗?

如果不是,是否有一些可能的推理将折叠权与无点编程联系起来?

【问题讨论】:

    标签: haskell fold pointfree


    【解决方案1】:

    您可以为此使用flip :: (a -> b -> c) -> b -> a -> c:

    fourth :: (a, b, c, Int) -> Int
    fourth (a, b, c, d) = d
    
    summerLeft :: Int -> (a, b, c, Int) -> Int
    summerLeft = flip ((+) . fourth)
    
    main :: IO ()
    main = print $ summerLeft 1 (2, 3, 4, 5)
    

    打印

    6
    

    【讨论】:

    • 嗯,这让我想起了画眉组合子 Txy = yx。看起来像一个通用的方法。谢谢。
    【解决方案2】:

    这是另一个解决方案:

    summerLeft n tuple = n + fourth tuple
    summerLeft n = (n +) . fourth
    summerLeft = (. fourth) . (+)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-15
      • 2013-04-13
      • 2014-09-03
      • 2017-04-11
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      相关资源
      最近更新 更多