Tacit function composition in Haskell

半城伤御伤魂 提交于 2019-12-22 02:00:59

问题


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?


回答1:


Applicative functors work pretty well here.

import Control.Applicative

mean = (/) <$> sum <*> (fromIntegral . length)



回答2:


Yes, your tacit function is liftM2 in the (->) r monad (liftM2 is in Control.Monad, and the function instance of Monad is in Control.Monad.Instances).

I found this using the pointfree program (you can install it via cabal install pointfree), invoked as:

$ pointfree '\xs -> sum xs / (fromIntegral $ length xs)'

(in a Unix terminal)



来源:https://stackoverflow.com/questions/12061176/tacit-function-composition-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!