packages feed

lhae-0.0.3: src/Controller/Menu/Statistics/FrequencyDistribution.hs

module Controller.Menu.Statistics.FrequencyDistribution (eventHandler)
    where

import Control.Monad (forM_)
import Data.List (nub)
import Controller (Controller,onGridView)
import qualified Controller.Grid as Grid
import Controller.Canonical (addRowExpr)
import Controller.Dialog (chooseColumnDialog)
import View.Component.Grid (getColumnValues)
import View.Dialog.Complex (okLabel)
import Model.CellContent (CellExpr(NumberExpr))
import Util (justWhen)
import I18n (__)

eventHandler :: Controller ()
eventHandler = do
  selection <- chooseColumnDialog (__ "Frequency Distribution") okLabel Nothing
  justWhen selection $ \colIndex ->
      do values <- onGridView $ getColumnValues colIndex
         Grid.new
         Grid.addColumns [__ "Frequency", __ "Percentage"]

         forM_ (freqDist values) $ \(value,freq,perc) ->
             do addRowExpr (Just value) 
                  [NumberExpr $ fromIntegral freq, NumberExpr perc]

freqDist :: [String] -> [(String,Int,Double)]
freqDist values =
    let unique = nub values
        frequency = map (\s -> length $ filter ((==) s) values) unique
        numValues = length values
        percentage = map (\f -> fromIntegral f / (fromIntegral numValues)) frequency
    in
      zip3 unique frequency percentage