haskell - Can some explain how the following code works? -
i doing coding challenge in codewar: write function avg calculates average of numbers in given list. solution works don't quite understand 1 of solutions of others. can explain?
avg :: [float] -> float avg = (/) <$> sum <*> fromintegral . length shouldn't be:
avg l = pure (/) <*> sum l <*> fromintegral . length $ l
this code uses applicative instance of (->) a type, defined here as:
instance applicative ((->) a) pure = const (<*>) f g x = f x (g x) you can interpret implementation thinking of naryfunction <$> f1 <*> f2 <*> ... <*> fn "apply same parameter n functions , apply resulting arguments naryfunction".
in case, (/) <$> sum <*> fromintegral . length can thought \ xs -> (/) (sum xs) ((fromintegral . length) xs) sum xs / fromintegral (length xs).
you can prove expanding expression 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)
Comments
Post a Comment