[英]Understanding the functions elem and isInfixOf
A while ago I've asked a question about the function elem
here , but I don't think the answer is fully satisfactory. 不久前,我在这里询问了有关函数elem
问题 ,但我认为答案并不完全令人满意。 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: 我们知道elem
属于反引号,因此elem
是一个中缀,我的解释是:
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
. 最后,它将返回True
因为它是any
而不是all
。 This looked good until I see a similar expression for isInfixOf
: 直到我看到与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]
Your problem is with the (** a)
syntactic sugar. 您的问题在于(** a)
语法糖。 The thing is that (elem b)
is just the partial application of elem, that is: 问题是(elem b)
只是elem的部分应用,即:
(elem b) == (\xs -> elem b xs)
However when we use back ticks to make elem infix, we get a special syntax for infix operators which works like this: 但是,当我们使用反斜杠使elem infix时,我们为infix运算符获得了一种特殊的语法,其工作方式如下:
(+ a) == (\ b -> b + a)
(a +) == (\ b -> a + b)
So therefore, 因此,
(`elem` xs) == (\a -> a `elem` xs) == (\ a -> elem a xs)
while 而
(elem xs) == (\a -> elem xs a)
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. 请注意, (** a)
语法糖适用于所有中缀运算符,但-
也是前缀运算符。 This exception from the rule is discussed here and here . 此处和此处讨论了该规则的例外情况。
Using back-ticks around a function name turns it into an infix operator. 在函数名称周围使用反引号会将其转换为中缀运算符。 So 所以
x `fun` y
is the same as 是相同的
fun x y
Haskell also has operator sections, fe (+ 1)
means \\x -> x + 1
. Haskell还具有运算符部分,fe (+ 1)
表示\\x -> x + 1
。
So 所以
(`elem` xs)
is the same as 是相同的
\x -> x `elem` xs
or 要么
\x -> elem x xs
or 要么
flip elem xs
It's called partial application . 这称为部分应用程序 。
isInfixOf [1, 2, 3]
returns a function that expects one parameter. isInfixOf [1, 2, 3]
返回一个需要一个参数的函数。
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. any (elem [1, 2]) [1, 2, 3]
是错误的,因为您正在寻找元素[1, 2]
,并且列表仅包含数字,因此haskell无法匹配类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.