'What is the meaning of comma separated names in brackets - as a binding?
In a document (https://riptutorial.com/Download/haskell-language.pdf), in Chapter 5: Arrows, I encountered the following example:
spaceAround :: Double -> [Double] -> Double
spaceAround x ys = minimum greater - maximum smaller where (greater, smaller) = partition (>x) ys
What does the expression (greater, smaller) mean?
Solution 1:[1]
The partition function returns a pair or 2-element tuple as its result. Assigning that tuple to (greater, smaller) assigns values of the first and second elements of the pair to the two variables greater and smaller respectively.
If you are familiar with the let... in syntax, another way of writing this function would be as follows:
spaceAround2 :: Double -> [Double] -> Double
spaceAround2 x ys =
let myPair = partition (>x) ys
greater = fst myPair
smaller = snd myPair
in minimum greater - maximum smaller
Solution 2:[2]
The mechanism is just called pattern matching.
It is eplained here:
Syntax in Functions
Pattern matching
...
Where!?
...
You can also use where bindings to pattern match! We could have rewritten the where section of our previous function as:
... where bmi = weight / height ^ 2 (skinny, normal, fat) = (18.5, 25.0, 30.0)...
Source: http://learnyouahaskell.com/syntax-in-functions
Hence, in the example that is provided with the question, the result of the function partition is split into the elements by mattern mathching.
Further tested example:
main :: IO ()
main = do
print e1
print e2
print e3
(e1, e2, e3) = (1, "Hello", "World!")
...it prints:
1
"Hello"
"World!"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
