We can use the point-free style or tacit programming to write programs where function definitions don’t have arguments. We combine other functions to build new functions rather than explicitly declaring arguments. In other words, we define the function through function composition.
Point-free functions perform the same function as normal functions. Here are some advantages of point-free functions:
let fn x = f (g (h x))
In the code above, we write a simple function definition without using point-free.
let fn = f . g . h
In this piece of code, we make use of point-free.
As seen above, it’s easy to understand the function defined on the right compared to the code on the left.
Let’s implement point-full and point-free styles in Haskell and observe the difference.
f :: Int -> Intf x = x + 1z :: Int -> Intz x = x * xg x = f(z x)main = print (g(4))
In the code above we implement the function * without point-free. The simple functions are combined together using a third function declaration which is .
The highlighted line in the code above shows the integration of the two functions and .
f :: Int -> Intf x = x + 1z :: Int -> Intz x = x * xg = f . zmain = print (g(4))
We’ve calculated * . Here, we use the function to compute . We use the function z to compute the square of whatever the argument is.
The primary function is , which combines and . If we see the highlighted line in both windows, we can see how the function g has no arguments in the latter windows and hence, is point-free.
When we combine multiple function declarations as one using point-free, it makes it easier to read codes. It also helps understand better, as shown below, given that multiple functions are being used.
summ :: Int -> Intsumm x = x + xsquared :: Int -> Intsquared x = x * xsubtractt :: Int -> Intsubtractt x = x - 5fin = summ . squared . subtracttmain = print (fin(4))
In this example shown above we use point free to implement the function - - . First, the function, subtractt
is called and then the result is squared
. The result of this function is then added to itself using point-free. The function integration of all these 3 functions is done using a fourth function fin
as shown in the highlighted line above.
Free Resources