Entropy: Difference between revisions

Content added Content deleted
(Added Wren)
(→‎{{header|Haskell}}: Added a variant, expressed in terms of an applicative.)
Line 1,094: Line 1,094:
where lg c = -c * logBase 2 c
where lg c = -c * logBase 2 c
fq c = let sc = sum c in map (/ sc) c</lang>
fq c = let sc = sum c in map (/ sc) c</lang>


Or, inlining with an applicative expression (turns out to be fractionally faster):

<lang haskell>import Data.List (genericLength, group, sort)

entropy
:: (Ord a, Floating c)
=> [a] -> c
entropy =
sum .
map (negate . ((*) <*> logBase 2)) .
(map =<< flip (/) . sum) . map genericLength . group . sort

main :: IO ()
main = print $ entropy "1223334444"</lang>


{{out}}
{{out}}