Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Add-Operation

In a Codefights challenge where you have to add two numbers the user kaiochao had a super minimalisic answer

add = (+)

How does it work and has this functionality a own name?

like image 263
Roman Avatar asked Jul 22 '26 03:07

Roman


1 Answers

Here's an explicit definition:

add a b = a + b

There is a feature in Haskell that says that we can rewrite a + b as (+) a b, this is due to the fact that operators are functions in Haskell. So we can rewrite:

add a b = (+) a b

But then we're doing nothing extra to the arguments of this function, so we can reduce this function by removing the explicit arguments*. Note that this requires an understanding of how function application in Haskell works:

add = (+)

This is because functions are data in Haskell. This is literally saying that plus and the function of addition are the same thing.

In practice, we can see this by substituting:

  add 1 2
= (+) 1 2 -- Since add = (+), this can be read literally.
= 1 + 2   -- This is how operators work in Haskell.
= 3       -- Calculation.

This is known as pointfree style in Haskell.


*As @Benjamin Hodgson mentioned, this is called eta-reduction.

like image 97
AJF Avatar answered Jul 23 '26 18:07

AJF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!