Util.hs 1.31 KB
Newer Older
Philipp Meyer's avatar
Philipp Meyer committed
1
module Util
2
3
    (verbosePut,Vector,value,elems,items,buildVector,makeVector,vmap,
     nubOrd,nubOrdBy)
Philipp Meyer's avatar
Philipp Meyer committed
4
5
where

6
import qualified Data.Map as M
Philipp Meyer's avatar
Philipp Meyer committed
7
import Control.Monad
8
9
10
import Data.List
import Data.Ord
import Data.Function
Philipp Meyer's avatar
Philipp Meyer committed
11
12
13
14
15

verbosePut :: Int -> Int -> String -> IO ()
verbosePut verbosity level str =
        when (verbosity >= level) (putStrLn str)

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

newtype Vector a = Vector { getVector :: M.Map a Integer }

instance (Show a) => Show (Vector a) where
        show (Vector v) =
                "[" ++ intercalate "," (map showEntry (M.toList v)) ++ "]"
            where showEntry (i,x) =
                    show i ++ (if x /= 1 then "(" ++ show x ++ ")" else "")

vmap :: (Ord a, Ord b) => (a -> b) -> Vector a -> Vector b
vmap f (Vector m) = Vector $ M.mapKeys f m

value :: (Ord a) => Vector a -> a -> Integer
value v x = M.findWithDefault 0 x (getVector v)

elems :: (Ord a) => Vector a -> [a]
elems = M.keys . getVector

items :: Vector a -> [(a,Integer)]
items = M.toList . getVector

buildVector :: (Ord a) => [(a, Integer)] -> Vector a
buildVector = makeVector . M.fromList

makeVector :: (Ord a) => M.Map a Integer -> Vector a
makeVector = Vector . M.filter (/=0)

nubOrd :: (Ord a) => [a] -> [a]
nubOrd = nubOrdBy id

nubOrdBy :: (Ord b) => (a -> b) -> [a] -> [a]
nubOrdBy f = map head . groupBy ((==) `on` f) . sortBy (comparing f)