niloy / blog

blog raw files
3 stars 1 forks source link

Things I learned & liked from Haskell #23

Open niloy opened 9 years ago

niloy commented 9 years ago

Currying

Every multi parameter function can be thought of accepting a single parameter and returning a partial function. Example, consider a sum function which accepts two numbers and returns the result.

sum(2, 3) -> 5 (Return type number)

But if only one argument is passed to the sum function, the return type would instead be a function.

sum(2) -> Function(partial) which accepts 1 argument and returns a number

While I was aware of this technique in javascript, but never thought that the concept could be generalized to any function.

Composing

Multiple functions can be composed together to make new functions. Example,

f = square . plus1

Assuming square squares a number and plus adds 1 to a number, the new function f would perform these two operations on any given number. So the following would be true:

f(2) = 5

The . is the compose operator in Haskell. The idea is to write very simple functions and combine them together to make more complex functions.

Any binary function can be written in infix notation

Haskell doesn't have a mod operator like %. Instead there is a function called mod which accepts two parameters. In Haskell, it can be written in both infix and prefix mode. The following two statements are equivalent.

5 mod 2

mod 5 2

Infinite Lists

Writing [1..] is a unbounded list. Calling length on such a list will hang the computer. But we can perform other array operations like head, take without causing infinite recursion. Haskell evaluates the infinite list lazily as much as it needs to.