Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tacit function composition in Haskell

Say I have a mean function defined like so:

mean xs = sum xs / (fromIntegral $ length xs)

but I want it in some tacit form, like this:

mean = sum / (fromIntegral . length)

Is there a built-in Haskell way to do something along these lines without having to build up my own tacit function (something like this):

tacit :: (a -> b -> c) -> (d -> a) -> (d -> b) -> d -> c
tacit a b c i = a (b i) (c i)

In this form, the function looks like this:

mean = tacit (/) sum (fromIntegral . length)

but it feels like there might be a way to avoid having to use an explicit function such as this. I'm just wondering; is there some way to do this that is built in to Haskell?

like image 551
Benjamin Kovach Avatar asked Aug 21 '12 18:08

Benjamin Kovach


People also ask

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.

What is a tacit programming language?

Tacit programming, also called point-free style, is a programming paradigm in which function definitions do not identify the arguments (or "points") on which they operate. Instead the definitions merely compose other functions, among which are combinators that manipulate the arguments.

What is point free code?

Point free style means that the code doesn't explicitly mention it's arguments, even though they exist and are being used. This works in Haskell because of the way functions work.


1 Answers

Applicative functors work pretty well here.

import Control.Applicative

mean = (/) <$> sum <*> (fromIntegral . length)
like image 66
Artyom Avatar answered Sep 24 '22 10:09

Artyom