简体   繁体   中英

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. 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]

Your problem is with the (** a) syntactic sugar. The thing is that (elem b) is just the partial application of elem, that is:

(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:

(+ 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. 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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM