문제

I have to create a boolean function in Haskell that receives a word (String) and a list of characters. The function has to verify that all chars in the list are included in the string. I made some research and found out that functions all and elem could be helpful.

Example:

word = "hello"
list = ['h','o','e']

My code looks something like this:

allCharBelong word list = all (`elem` word) list

I made some testing and it works perfectly (If you want to double-check that would be nice).

My question is: Why when I take out the backticks in elem, the function don't work?

Working: allCharBelong word list = all (`elem` word) list

Not working: allCharBelong word list = all (elem word) list

도움이 되었습니까?

해결책

(`elem` word) is an operator section that partially applies the second argument, it is equivalent to \x -> elem x word whereas elem word = (word `elem`) = \x -> elem word x. It helps to annotate expressions with types to figure out what's going on sometimes.

다른 팁

It doesn't work because whereas in the first case you have what it's called a "section", i.e. a partial application of an infix operator where -in this case- you fixed the second argument, in the second case you fix the first parameter.

ghci> :t elem "string"
elem "string" :: [[Char]] -> Bool
ghci> :t (`elem` "string")
(`elem` "string") :: Char -> Bool

Adding backticks makes the function infix. elem is a binary operator when used in infix form. Putting an argument before or after an infix operator determines which of the arguments we're applying to:

(`elem` word) === \char -> elem char word -- apply to second arg
(char `elem`) === \word -> elem char word -- apply to first arg

elem without the backticks is just a regular curried function:

elem char === \word -> elem char word -- can only apply partially to first arg

(`op` val) is an (IMO quite nice, because the backticks are so unobstrusive for reading) alternative writing for flip op val: it allows you to partially apply a function in its second, rather than first, argument.

Such operator sections are of course more commonly used with functions that are already in infix form, e.g.

Prelude> map (!!4) ["....Hello", "...Hello", "..Hello", ".Hello", "Hello"]
"Hello"
Prelude> map (/2) [10,20,30,40]
[5.0,10.0,15.0,20.0]

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top