简体   繁体   English

有人可以解释下面的代码如何工作?

[英]Can some explain how the following code works?

I am doing a coding challenge in codewar: Write function avg which calculates average of numbers in given list. 我在codewar中进行编码挑战:编写函数avg,它计算给定列表中的数字平均值。 My solution works but I don't quite understand one of the solutions of others. 我的解决方案有效,但我不太了解其他解决方案。 Can anyone explain? 谁能解释一下?

avg :: [Float] -> Float
avg = (/) <$> sum <*> fromIntegral . length

Shouldn't it be: 不应该是:

avg l = pure (/) <*> sum l <*> fromIntegral . length  $ l 

This code uses the Applicative instance of the (->) a type, which is defined here as: 此代码使用(->) a类型的Applicative实例, 此处定义为:

instance Applicative ((->) a) where
    pure = const
    (<*>) f g x = f x (g x)

You can interpret this implementation by thinking of naryFunction <$> f1 <*> f2 <*> ... <*> fn as "apply the same parameter to all n functions and apply the resulting arguments to naryFunction ". 您可以通过将naryFunction <$> f1 <*> f2 <*> ... <*> fn视为“将相同参数应用于所有n个函数并将结果参数应用于naryFunction ”来解释此实现。

In your case, (/) <$> sum <*> fromIntegral . length 在你的情况下, (/) <$> sum <*> fromIntegral . length (/) <$> sum <*> fromIntegral . length can be thought as \\ xs -> (/) (sum xs) ((fromIntegral . length) xs) which is just sum xs / fromIntegral (length xs) . (/) <$> sum <*> fromIntegral . length可以被认为是\\ xs -> (/) (sum xs) ((fromIntegral . length) xs) ,它只是sum xs / fromIntegral (length xs)

You can prove this by simply expanding your expression with the definition of (<*>) : 您可以通过简单地使用(<*>)的定义扩展表达式来证明这一点:

avg = (/) <$> sum <*> fromIntegral . length
avg = fmap (/) sum <*> fromIntegral . length
avg xs = (fmap (/) sum) xs ((fromIntegral . length) xs)
avg xs = ((/) . sum xs) (fromIntegral (length xs))  -- fmap f g = f . g
avg xs = sum xs / fromIntegral (length xs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM