Averages/Pythagorean means: Difference between revisions
Content added Content deleted
(→JS ES6: Updated primitives, consolidated test with mapFromList and applicative ap) |
(→{{header|Haskell}}: Added an alternative, defining the functions applicatively, and testing with (and zipWith (>=))) |
||
Line 1,220: | Line 1,220: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
====One generalized function==== |
|||
The [[wp:Generalized mean|general function]] given here yields an arithmetic mean when its first argument is <code>1</code>, a geometric mean when its first argument is <code>0</code>, and a harmonic mean when its first argument is <code>-1</code>. |
The [[wp:Generalized mean|general function]] given here yields an arithmetic mean when its first argument is <code>1</code>, a geometric mean when its first argument is <code>0</code>, and a harmonic mean when its first argument is <code>-1</code>. |
||
Line 1,233: | Line 1,234: | ||
mapM_ (\(t,m) -> putStrLn $ t : ": " ++ show m) ms |
mapM_ (\(t,m) -> putStrLn $ t : ": " ++ show m) ms |
||
putStrLn $ " a >= g >= h is " ++ show ((\(_,[a,g,h])-> a>=g && g>=h) (unzip ms))</lang> |
putStrLn $ " a >= g >= h is " ++ show ((\(_,[a,g,h])-> a>=g && g>=h) (unzip ms))</lang> |
||
====Three applicatively defined functions==== |
|||
These three functions share the same liftM2 structure, which can be expressed applicatively as '''pure f <*> f1 <*> f2''' |
|||
<lang haskell>import Data.List (genericLength) |
|||
-- ARITHMETIC, GEOMETRIC AND HARMONIC MEANS ----------------------- |
|||
arithmetic, geometric, harmonic :: [Double] -> Double |
|||
arithmetic = pure (/) <*> sum <*> genericLength |
|||
geometric = pure (**) <*> product <*> ((1 /) . genericLength) |
|||
harmonic = pure (/) <*> genericLength <*> foldr ((+) . (1 /)) 0 |
|||
-- TEST ----------------------------------------------------------- |
|||
xs :: [Double] |
|||
xs = [arithmetic, geometric, harmonic] <*> [[1 .. 10]] |
|||
main :: IO () |
|||
main = |
|||
(putStrLn . unlines) |
|||
[ zip ["Arithmetic", "Geometric", "Harmonic"] xs >>= show |
|||
, mappend "\n A >= G >= H is " $ -- |
|||
(show . and) $ zipWith (>=) xs (tail xs) |
|||
]</lang> |
|||
{{Out}} |
|||
<pre>("Arithmetic",5.5)("Geometric",4.528728688116765)("Harmonic",3.414171521474055) |
|||
a >= g >= h is True</pre> |
|||
=={{header|HicEst}}== |
=={{header|HicEst}}== |