-
Notifications
You must be signed in to change notification settings - Fork 2
/
Mrifk_util.hs
61 lines (42 loc) · 1.74 KB
/
Mrifk_util.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
51
52
53
54
55
56
57
58
59
60
61
{-
Mrifk, a decompiler for Glulx story files.
Copyright 2004 Ben Rudiak-Gould.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You can read the GNU General Public License at this URL:
http://www.gnu.org/copyleft/gpl.html
-}
module Mrifk_util (
makeLookupTable, tableLookup,
sortFst, uniqBy,
onFst
) where
import Data.List (sortBy)
onFst f (a,b) = (f a,b)
makeLookupTable :: (Ord a) => [(a,b)] -> LookupTable a b
tableLookup :: (Ord a) => a -> LookupTable a b -> Maybe b
data LookupTable a b =
LookupTableBranch (LookupTable a b) a b (LookupTable a b) | LookupTableLeaf
makeLookupTable = makeLookupTable' . uniqFst . sortFst
makeLookupTable' [] = LookupTableLeaf
makeLookupTable' x =
let (left,((p,q):right)) = splitAt (length x `div` 2) x
in LookupTableBranch (makeLookupTable' left) p q (makeLookupTable' right)
tableLookup x LookupTableLeaf = Nothing
tableLookup x (LookupTableBranch left x' y right) =
case x `compare` x' of
EQ -> Just y
LT -> tableLookup x left
GT -> tableLookup x right
uniqBy eq (x:xs) = x : uniqBy eq (dropWhile (eq x) xs)
uniqBy eq [] = []
uniqFst :: (Eq a) => [(a,b)] -> [(a,b)]
uniqFst = uniqBy (\(a,_) (b,_) -> a == b)
sortFst :: (Ord a) => [(a,b)] -> [(a,b)]
sortFst = sortBy (\(a,_) (b,_) -> a `compare` b)