;; statistics.hs — mean, variance, std-dev on a [Double].
;; Source: classic textbook example.
;;
;; Exercises Phase 10: `fromIntegral`, `/`, `sqrt`, list ops on `[Double]`.

(define
  hk-prog-val
  (fn
    (src name)
    (hk-deep-force (get (hk-eval-program (hk-core src)) name))))

(define
  hk-stats-source
  "mean xs = sum xs / fromIntegral (length xs)\n\nvariance xs = let m = mean xs\n                  sqDiff x = (x - m) * (x - m)\n              in sum (map sqDiff xs) / fromIntegral (length xs)\n\nstdDev xs = sqrt (variance xs)\n")

(hk-test
  "statistics.hs — mean [1,2,3,4,5] = 3"
  (hk-prog-val (str hk-stats-source "r = mean [1.0,2.0,3.0,4.0,5.0]\n") "r")
  3)

(hk-test
  "statistics.hs — mean [10,20,30] = 20"
  (hk-prog-val (str hk-stats-source "r = mean [10.0,20.0,30.0]\n") "r")
  20)

(hk-test
  "statistics.hs — variance [2,4,4,4,5,5,7,9] = 4"
  (hk-prog-val
    (str hk-stats-source "r = variance [2.0,4.0,4.0,4.0,5.0,5.0,7.0,9.0]\n")
    "r")
  4)

(hk-test
  "statistics.hs — stdDev [2,4,4,4,5,5,7,9] = 2"
  (hk-prog-val
    (str hk-stats-source "r = stdDev [2.0,4.0,4.0,4.0,5.0,5.0,7.0,9.0]\n")
    "r")
  2)

(hk-test
  "statistics.hs — variance of constant list = 0"
  (hk-prog-val (str hk-stats-source "r = variance [5.0,5.0,5.0,5.0]\n") "r")
  0)

{:fails hk-test-fails :pass hk-test-pass :fail hk-test-fail}
