【问题标题】:Trying to write a function point free, GHCI does not approve试图免费写一个功能点,GHCI不赞成
【发布时间】:2011-12-28 02:20:43
【问题描述】:

作为练习,我正在尝试手动实现前奏中有趣的部分。每当我发现有机会免费得分时,我都会抓住它。然而,这让我在最不可能的地方找到了一堵砖墙。使用此代码:

myelem _ [] = False 
myelem x y  = if x == head y then True else myelem x (tail y)

我正在尝试实现notElem。以下是我的尝试:

-- First
mynotelem = not myelem

由于类型不匹配而爆炸,这是可以理解的。这很容易解决:

-- Second
mynotelem x y = not (myelem x y)

但是参数 x 和 y 的显式声明感觉丑陋且不必要,所以我尝试将其恢复为无点样式。

-- Third
mynotelem = not $ myelem

失败了

 Couldn't match expected type `Bool'
         with actual type `a0 -> [a0] -> Bool'
 In the second argument of `($)', namely `myelem'
 In the expression: not $ myelem
 In an equation for `mynotelem': mynotelem = not $ myelem

很公平,类型仍然不匹配。但是你如何解决它?再次,您可以直接跳转到

-- Fourth
mynotelem x y = not $ myelem x y

这可行,但似乎很危险地接近于绕圈子。我发现可以消除其中一个论点:

-- Fifth
mynotelem x = not . (myelem x)

但那个讨厌的 x 仍然存在。如何消除它?

【问题讨论】:

  • ThelronKnuckle:如果您还没有,请在 SO 问题中搜索有关 ($)(.) 之间区别的问题 - 我认为您会发现这些问题/答案很有帮助。

标签: haskell ghc ghci pointfree


【解决方案1】:

我们可以这样重写你的代码:

mynotelem x = not . (myelem x)
            = (not .) (myelem x)

现在认识到这只是h x = f (g x)f = (not .)g = myelem,所以我们可以用(.) 运算符作为h = f . g 的另一种用法来编写它:

mynotelem = (not .) . myelem

请注意当使用具有更多参数的函数组合时模式如何继续:

> let f x y z = x+y+z
> (((sqrt .) .) . f) 1 2 3
2.449489742783178

或者,您也可以使用这种看起来很有趣的组合运算符组合来编写它:

mynotelem = ((.).(.)) not myelem

对于更多参数,模式继续如下:

> ((.).(.).(.)) sqrt f 1 2 3
2.449489742783178

【讨论】:

  • 无耻外挂,我把“composition”包上传到hackage,为boob操作者和朋友提供方便的功能。
  • 布布操作员 XD 在向我的伙伴拉皮条时必须利用它作为优势
  • 在实际代码中使用“boob operator”是否普遍?处理这种情况的最干净的方法是什么?保留它的要点会更好吗(mynotelem x = not . elem xmynotelem x y = not $ elem x y)?
猜你喜欢
  • 1970-01-01
  • 2014-08-03
  • 2021-11-09
  • 1970-01-01
  • 1970-01-01
  • 2013-03-21
  • 1970-01-01
  • 2019-07-29
  • 2012-10-15
相关资源
最近更新 更多