【问题标题】:Dot operator in haskell with multi-parameter functions具有多参数功能的haskell中的点运算符
【发布时间】:2012-11-08 15:05:22
【问题描述】:

我想在 haskell 中编写一个无点函数,为了简单起见,假设我想做这个函数:

maxmin :: Ord a => a -> a -> a -> a
maxmin a b c = max a (min b c)

我可以改进一下

maxmin a b = (max a) . (min b)

但是有什么办法可以去掉 a 和 b?

【问题讨论】:

  • 无点是一种代码风格,因此只有在提高可读性时才应使用;无点符号编译方式不同(因为内联)的情况通常不是您需要担心的(在分析之后考虑一下)。在您的情况下,我会说无点无济于事。例如,将 maxmin 重命名为 constrainTo 将是一个更具表现力的更改。

标签: haskell pointfree dot-operator


【解决方案1】:

我不会说这更简单,但你去吧:

maxmin :: Ord a => a -> a -> a -> a                                             
maxmin = (. min) . (.) . max 

(使用来自lambdabothttp://www.haskell.org/haskellwiki/Pointfreepl 工具生成)

lambdabot> pl maxmin a b c = max a (min b c)
maxmin = (. min) . (.) . max

【讨论】:

    【解决方案2】:

    您只需为此使用"three laws of sections"

    (a `op` b) = (a `op`) b = (`op` b) a = op a b
    

    这样

    import Control.Arrow
    
    maxmin a b = (max a) . (min b)
               = (.) (max a) (min b)
               = uncurry (.) (max a, min b)
               = uncurry (.) . (max *** min) $ (a, b)
               = curry (uncurry (.) . (max *** min)) a b
    

    这也不太可读。 :)

    【讨论】:

      猜你喜欢
      • 2014-09-08
      • 1970-01-01
      • 2011-02-19
      • 2010-12-28
      • 1970-01-01
      • 2016-12-21
      • 1970-01-01
      • 2013-06-13
      相关资源
      最近更新 更多