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?
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.
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.
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.
Applicative functors work pretty well here.
import Control.Applicative
mean = (/) <$> sum <*> (fromIntegral . length)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With