理解函数 elem 和 isInfixOf
不久前,我在此处elem函数的问题>,但我认为答案并不完全令人满意。我的问题是关于表达式的:
any (`elem` [1, 2]) [1, 2, 3]
我们知道 elem
位于反引号中,因此 elem
是一个中缀,我的解释是:
1 `elem` [1, 2] -- True
2 `elem` [1, 2] -- True
3 `elem` [1, 2] -- False
最后它将返回 True
因为它是任何
而不是全部
。这看起来不错,直到我看到 isInfixOf
的类似表达式:
any (isInfixOf [1, 2, 3]) [[1, 2, 3, 4], [1, 2]]
在这种情况下,一个合理的解释似乎是:
isInfixOf [1, 2, 3] [1, 2, 3, 4] -- True
isInfixOf [1, 2, 3] [1, 2] -- False
我想知道为什么它们以如此不同的方式使用,因为
any (elem [1, 2]) [1, 2, 3]
会给出错误,所以会
any (`isInfixOf` [[1, 2, 3, 4], [1, 2]]) [1, 2, 3]
A while ago I've asked a question about the function elem
here, but I don't think the answer is fully satisfactory. My question is about the expression:
any (`elem` [1, 2]) [1, 2, 3]
We know elem
is in a backtick so elem
is an infix and my explanation is:
1 `elem` [1, 2] -- True
2 `elem` [1, 2] -- True
3 `elem` [1, 2] -- False
Finally it will return True
since it's any
rather than all
. This looked good until I see a similar expression for isInfixOf
:
any (isInfixOf [1, 2, 3]) [[1, 2, 3, 4], [1, 2]]
In this case a plausible explanation seems to be:
isInfixOf [1, 2, 3] [1, 2, 3, 4] -- True
isInfixOf [1, 2, 3] [1, 2] -- False
I wonder why they've been used in such different ways since
any (elem [1, 2]) [1, 2, 3]
will give an error and so will
any (`isInfixOf` [[1, 2, 3, 4], [1, 2]]) [1, 2, 3]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的问题在于
(** a)
语法糖。问题是(elem b)
只是 elem 的部分应用,即:但是,当我们使用反引号使 elem 中缀时,我们会得到一个特殊的中缀运算符语法,其工作原理如下:
因此,
虽然
在后一种情况下你的参数顺序错误,但这就是你的代码中发生的情况。
请注意,
(** a)
语法糖适用于除-
之外的所有中缀运算符,因为它也是前缀运算符。 此处和讨论了该规则的例外情况/5210182/the-difference- Between-1-and-1">此处。Your problem is with the
(** a)
syntactic sugar. The thing is that(elem b)
is just the partial application of elem, that is:However when we use back ticks to make elem infix, we get a special syntax for infix operators which works like this:
So therefore,
while
So in the latter case your arguments are in the wrong order, and that is what is happening in your code.
Note that the
(** a)
syntactic sugar works for all infix operators except-
since it is also a prefix operator. This exception from the rule is discussed here and here.在函数名称周围使用反引号会将其变成中缀运算符。所以
与 Haskell 也有运算符部分一样
,fe
(+ 1)
表示\x -> x + 1 。
所以
相同
与or
or
Using back-ticks around a function name turns it into an infix operator. So
is the same as
Haskell also has operator sections, f.e.
(+ 1)
means\x -> x + 1
.So
is the same as
or
or
它称为部分应用。
isInfixOf [1, 2, 3]
返回一个需要一个参数的函数。any (elem [1, 2]) [1, 2, 3]
是一个错误,因为您正在查找元素[1, 2]
,并且列表仅包含数字,因此 haskell 无法匹配类型。It's called partial application.
isInfixOf [1, 2, 3]
returns a function that expects one parameter.any (elem [1, 2]) [1, 2, 3]
is an error because you're looking for an element[1, 2]
, and the list only contains numbers, so haskell cannot match the types.