Haskell中的默认函数组合 [英] Tacit function composition in Haskell
本文介绍了Haskell中的默认函数组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
平均值
函数: 意思是xs = sum xs /(fromIntegral $ length xs)
但我希望它有些默契的形式,像这样:
mean = sum /(fromIntegral。length)
是否有一种内置的Haskell方式来执行这些操作,而无需构建自己的 tacit
函数(如下所示):
tacit ::(a - > b - > c) - > (d→a)→> (d→b)→> d - > c
tacit abci = a(bi)(ci)
在这种形式下,函数看起来像这样:
mean = tacit(/)sum(fromIntegral。length)
但感觉好像有一种方法可以避免使用像这样的显式函数。我是在想;有什么办法可以做到这一点,内置到哈斯克尔?
解决方案
应用函子在这里工作得很好。
import Control.Applicative
mean =(/)< $>总和* (fromIntegral。length)
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?
解决方案
Applicative functors work pretty well here.
import Control.Applicative
mean = (/) <$> sum <*> (fromIntegral . length)
这篇关于Haskell中的默认函数组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文