Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell dot operator

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
like image 706
Roman Avatar asked May 14 '10 13:05

Roman


People also ask

What does the dot operator do in Haskell?

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.

What does a period do in Haskell?

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

What is the dot operator in Python?

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.

What is function composition in Haskell?

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.


1 Answers

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
like image 166
Daniel Martin Avatar answered Sep 30 '22 08:09

Daniel Martin