I try to develop a simple average function in Haskell. This seems to work:
lst = [1, 3]
x = fromIntegral (sum lst)
y = fromIntegral(length lst)
z = x / y
But why doesn't the following version work?
lst = [1, 3]
x = fromIntegral.sum lst
y = fromIntegral.length lst
z = x / y
Dot operator in Haskell is completely similar to mathematics composition: f{g(x)} where g() is a function and its output used as an input of another function, that is, f(). The result of . (dot) operator is another function (or lambada) that you can use and call it.
In general terms, where f and g are functions, (f . g) x means the same as f (g x). In other words, the period is used to take the result from the function on the right, feed it as a parameter to the function on the left, and return a new function that represents this computation."
Dot notation indicates that you're accessing data or behaviors for a particular object type. When you use dot notation, you indicate to Python that you want to either run a particular operation on, or to access a particular property of, an object type.
Composing functions is a common and useful way to create new functions in Haskell. Haskell composition is based on the idea of function composition in mathematics. In mathematics, if you have two functions f(x) and g(x), you compute their composition as f(g(x)). The expression f(g(x)) first calls g and then calls f.
You're getting tripped up by haskell's precedence rules for operators, which are confusing.
When you write
x = fromIntegral.sum lst
Haskell sees that as the same as:
x = fromIntegral.(sum lst)
What you meant to write was:
x = (fromIntegral.sum) lst
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With