Averages/Pythagorean means: Difference between revisions
Content added Content deleted
(→Haskell Three applicatively defined functions: Replaced liftM2 with liftA2) |
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 |
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 |
<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 = |
arithmetic = (/) . sum <*> genericLength |
||
geometric = |
geometric = (**) . product <*> ((1 /) . genericLength) |
||
harmonic = |
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) |