Averages/Pythagorean means: Difference between revisions

Content added Content deleted
m (→‎{{header|Python}}: Applied pylint (-> minor spacing and parenthesis adjustments))
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 '''liftM2''' structure, which can be expressed applicatively as '''pure f <*> f1 <*> f2'''
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.


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


-- ARITHMETIC, GEOMETRIC AND HARMONIC MEANS -----------------------
-- ARITHMETIC, GEOMETRIC AND HARMONIC MEANS ---------------
arithmetic, geometric, harmonic :: [Double] -> Double
arithmetic = liftM2 (/) sum genericLength


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


harmonic = liftM2 (/) genericLength (foldr ((+) . (1 /)) 0)
geometric = liftA2 (**) product ((1 /) . genericLength)


harmonic = liftA2 (/) genericLength (foldr ((+) . (1 /)) 0)
-- GENERIC --------------------------------------------------------
liftM2 f g h = pure f <*> g <*> h


-- TEST -----------------------------------------------------------
-- TEST ---------------------------------------------------
xs :: [Double]
xs :: [Double]
xs = [arithmetic, geometric, harmonic] <*> [[1 .. 10]]
xs = [arithmetic, geometric, harmonic] <*> [[1 .. 10]]
Line 1,284: Line 1,283:
, 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)