Averages/Pythagorean means: Difference between revisions

Content added Content deleted
m (→‎Three applicatively defined functions: liftA2 -> ((.) ... <*>))
Line 1,259: Line 1,259:


====Three applicatively defined functions====
====Three applicatively defined functions====
These three functions (each combining the length of a list with some kind of fold over the elements of that same list), all share the same general '''liftA2''' structure.
These three functions (each combining the length of a list with some kind of fold over the elements of that same list), all share the same applicative structure.


<lang haskell>import Control.Applicative (liftA2)
<lang haskell>import Data.List (genericLength)
import Data.List (genericLength)


-- ARITHMETIC, GEOMETRIC AND HARMONIC MEANS ---------------
-- ARITHMETIC, GEOMETRIC AND HARMONIC MEANS ---------------

arithmetic, geometric, harmonic :: [Double] -> Double
arithmetic, geometric, harmonic :: [Double] -> Double
arithmetic = liftA2 (/) sum genericLength
arithmetic = (/) . sum <*> genericLength


geometric = liftA2 (**) product ((1 /) . genericLength)
geometric = (**) . product <*> ((1 /) . genericLength)


harmonic = liftA2 (/) genericLength (foldr ((+) . (1 /)) 0)
harmonic = (/) . genericLength <*> foldr ((+) . (1 /)) 0


-- TEST ---------------------------------------------------
-- TEST ---------------------------------------------------
Line 1,283: Line 1,281:
, mappend "\n A >= G >= H is " $ --
, mappend "\n A >= G >= H is " $ --
(show . and) $ zipWith (>=) xs (tail xs)
(show . and) $ zipWith (>=) xs (tail xs)
]
]</lang>
</lang>
{{Out}}
{{Out}}
<pre>("Arithmetic",5.5)("Geometric",4.528728688116765)("Harmonic",3.414171521474055)
<pre>("Arithmetic",5.5)("Geometric",4.528728688116765)("Harmonic",3.414171521474055)