# $Id: moments.pliant,v 1.0 2002/02/08 12:43:00 dada Exp $
# http://dada.perl.it/shootout/

module "/pliant/language/context.pli"
module "/pliant/language/stream.pli"
module "/pliant/language/stream/pipe.pli"

function heapsort n ra
  arg Int n ; arg_rw Array:Int ra
  var Int rra
  var Int i
  var Int j
  var Int l := (n\2) + 1
  var Int ir := n
  
  part heapsort_loop
    if l>1
      l := l - 1
      rra := ra:l
    else
      rra := ra:ir
      ra:ir := ra:1
      ir := ir - 1
      if ir=1
        ra:1 := rra
        leave heapsort_loop
    i := l
    j := l*2

    while j<=ir
      if j<ir and ra:j < ra:(j+1)
        j := j + 1
      if rra < ra:j
        ra:i := ra:j
        i := j
        j := j + i
      else
        j := ir + 1
    ra:i := rra
    restart heapsort_loop


gvar Str line := ""
(gvar Stream STDIN) open "handle:0" in
gvar Array:Int nums
gvar uInt sum := 0
gvar Int i
gvar Int n
gvar Int mid
gvar Float mean
gvar Float deviation
gvar Float average_deviation := 0
gvar Float standard_deviation := 0
gvar Float variance := 0
gvar Float devpow3
gvar Float skew := 0
gvar Float kurtosis := 0
gvar Float median

while (STDIN atend) = false
  line := STDIN readline
  i := 0
  if(line parse i any)
    nums += i

for i 0 nums:size-1
  sum += nums:i

n := nums:size
mean := sum/n

for i 0 nums:size-1
  deviation := nums:i - mean
  average_deviation := average_deviation + (abs deviation)
  variance := variance + ((abs deviation) ^ 2.0)
  devpow3 := (abs deviation) ^ 3.0
  if deviation < 0
    devpow3 := -devpow3
  skew := skew + devpow3
  kurtosis := kurtosis + ((abs deviation) ^ 4.0)

average_deviation := average_deviation / n
variance := variance / (n-1)
standard_deviation := variance^0.5

if variance <> 0
  skew := skew / (n * variance * standard_deviation)
  kurtosis := kurtosis / (n * variance * variance) - 3.0


heapsort n nums
mid := n\2
median := shunt (n%2>0) nums:mid (nums:mid+nums:mid-1)/2

console "n:                  " n eol
console "median:             " (string median "fixed 6") eol
console "mean:               " (string mean "fixed 6") eol
console "average_deviation:  " (string average_deviation "fixed 6") eol
console "standard_deviation: " (string standard_deviation "fixed 6") eol
console "variance:           " (string variance "fixed 6") eol
console "skew:               " (string skew "fixed 6") eol
console "kurtosis:           " (string kurtosis "fixed 6") eol