Commit a9249f98 authored by Tom Bower's avatar Tom Bower
Browse files
parents 55a99caf b9c23d59
module Bdds where
import Data.List
import Data.Maybe
type Index = Int
data BExp = Prim Bool | IdRef Index | Not BExp | And BExp BExp | Or BExp BExp
deriving (Eq, Ord, Show)
type Env = [(Index, Bool)]
type NodeId = Int
type BDDNode = (NodeId, (Index, NodeId, NodeId))
type BDD = (NodeId, [BDDNode])
------------------------------------------------------
-- PART I
-- Pre: The item is in the given table
lookUp :: Eq a => a -> [(a, b)] -> b
lookUp item ((key, value):dict)
| item == key = value
| otherwise = lookUp item dict
checkSat :: BDD -> Env -> Bool
checkSat (start, nodes) env
= checkSat' start nodes env
where
checkSat' id ns vars
| id == 0 = False
| id == 1 = True
| otherwise = if var then checkSat' trueId ns vars
else checkSat' falseId ns vars
where
(varIndex, falseId, trueId) = lookUp id ns
var = lookUp varIndex vars
sat :: BDD -> [[(Index, Bool)]]
sat (start, nodes)
= sat' start nodes [] []
where
sat' id ns env foundEnvs
| id == 0 = []
| id == 1 = [env]
| otherwise = sat' trueId ns ((varIndex, True):env) foundEnvs
++ sat' falseId ns ((varIndex, False):env) foundEnvs
where
(varIndex, falseId, trueId) = lookUp id ns
------------------------------------------------------
-- PART II
simplify :: BExp -> BExp
simplify (Not (Prim bool))
= Prim (not bool)
simplify (And (Prim b1) (Prim b2))
= Prim (b1 && b2)
simplify (Or (Prim b1) (Prim b2))
= Prim (b1 || b2)
simplify other
= other
restrict :: BExp -> Index -> Bool -> BExp
restrict expr i val
= simplify (restrict' expr)
where
restr e = restrict e i val
restrict' expr@(IdRef index)
| index == i = Prim val
| otherwise = expr
restrict' (Not expr)
= Not (restr expr)
restrict' (And l r)
= And (restr l) (restr r)
restrict' (Or l r)
= Or (restr l) (restr r)
restrict' any
= any
-- Alternative approach. Tbh the one with the helper is much neater.
-- restrict :: BExp -> Index -> Bool -> BExp
-- restrict expr@(IdRef index) i val
-- | index == i = Prim val
-- | otherwise = expr
-- restrict (Not expr) i val
-- = simplify (Not (restrict expr i val))
-- restrict (And left right) i val
-- = simplify (And (restrict left i val) (restrict right i val))
-- restrict (Or left right) i val
-- = simplify (Or (restrict left i val) (restrict right i val))
-- restrict bool _ _
-- = bool
------------------------------------------------------
-- PART III
-- Pre: Each variable index in the BExp appears exactly once
-- in the Index list; there are no other elements
-- The question suggests the following definition (in terms of buildBDD')
-- but you are free to implement the function differently if you wish.
buildBDD :: BExp -> [Index] -> BDD
buildBDD e xs
= buildBDD' e 2 xs
-- Potential helper function for buildBDD which you are free
-- to define/modify/ignore/delete/embed as you see fit.
buildBDD' :: BExp -> NodeId -> [Index] -> BDD
buildBDD' (Prim b) id []
= ((if b then 1 else 0), [])
buildBDD' e id (x:xs)
= (id, node:(leftNodes ++ rightNodes))
where
restrict' = restrict e x
(leftId, leftNodes) = buildBDD' (restrict' False) (id * 2) xs
(rightId, rightNodes) = buildBDD' (restrict' True) (id * 2 + 1) xs
node = (id, (x, leftId, rightId))
------------------------------------------------------
-- PART IV
-- Done only half of Part IV
-- Pre: Each variable index in the BExp appears exactly once
-- in the Index list; there are no other elements
buildROBDD :: BExp -> [Index] -> BDD
buildROBDD e xs
= buildROBDD' e 2 xs
-- first optimisation from spec
-- wrong?
eqSubTrees :: BDDNode -> Bool
eqSubTrees (_, (_, l, r))
= l == r
buildROBDD' :: BExp -> NodeId -> [Index] -> BDD
buildROBDD' (Prim b) _ []
= ((if b then 1 else 0), [])
buildROBDD' e id (x:xs)
| eqSubTrees node = (leftId, nodes)
| otherwise = (id, node:nodes)
where
restrict' = restrict e x
(leftId, leftNodes) = buildROBDD' (restrict' False) (id * 2) xs
(rightId, rightNodes) = buildROBDD' (restrict' True) (id * 2 + 1) xs
node = (id, (x, leftId, rightId))
nodes = leftNodes ++ rightNodes
------------------------------------------------------
-- Examples for testing...
b1, b2, b3, b4, b5, b6, b7, b8 :: BExp
b1 = Prim False
b2 = Not (And (IdRef 1) (Or (Prim False) (IdRef 2)))
b3 = And (IdRef 1) (Prim True)
b4 = And (IdRef 7) (Or (IdRef 2) (Not (IdRef 3)))
b5 = Not (And (IdRef 7) (Or (IdRef 2) (Not (IdRef 3))))
b6 = Or (And (IdRef 1) (IdRef 2)) (And (IdRef 3) (IdRef 4))
b7 = Or (Not (IdRef 3)) (Or (IdRef 2) (Not (IdRef 9)))
b8 = Or (IdRef 1) (Not (IdRef 1))
bdd1, bdd2, bdd3, bdd4, bdd5, bdd6, bdd7, bdd8 :: BDD
bdd1 = (0,[])
bdd2 = (2,[(4,(2,1,1)),(5,(2,1,0)),(2,(1,4,5))])
bdd3 = (5,[(5,(1,0,1))])
bdd4 = (2,[(2,(2,4,5)),(4,(3,8,9)),(8,(7,0,1)),(9,(7,0,0)),
(5,(3,10,11)),(10,(7,0,1)),(11,(7,0,1))])
bdd5 = (3,[(4,(3,8,9)),(3,(2,4,5)),(8,(7,1,0)),(9,(7,1,1)),
(5,(3,10,11)),(10,(7,1,0)),(11,(7,1,0))])
bdd6 = (2,[(2,(1,4,5)),(4,(2,8,9)),(8,(3,16,17)),(16,(4,0,0)),
(17,(4,0,1)),(9,(3,18,19)),(18,(4,0,0)),(19,(4,0,1)),
(5,(2,10,11)),(10,(3,20,21)),(20,(4,0,0)),(21,(4,0,1)),
(11,(3,22,23)),(22,(4,1,1)),(23,(4,1,1))])
bdd7 = (6,[(6,(2,4,5)),(4,(3,8,9)),(8,(9,1,1)),(9,(9,1,0)),
(5,(3,10,11)),(10,(9,1,1)),(11,(9,1,1))])
bdd8 = (2,[(2,(1,1,1))])
import Data.List
data SuffixTree = Leaf Int | Node [(String, SuffixTree)]
deriving (Eq, Show)
------------------------------------------------------
isPrefix :: String -> String -> Bool
isPrefix pfix str
= pfix == take (length pfix) str
removePrefix :: String -> String -> String
--Pre: s is a prefix of s'
removePrefix
= drop . length
suffixes :: [a] -> [[a]]
suffixes str
= take (length str) (iterate tail str)
isSubstring :: String -> String -> Bool
isSubstring sub
= (any $ isPrefix sub) . suffixes
findSubstrings :: String -> String -> [Int]
findSubstrings sub str
= map fst $ filter (isPrefix sub . snd) (zip [0..] (suffixes str))
------------------------------------------------------
getIndices :: SuffixTree -> [Int]
getIndices (Leaf n)
= [n]
getIndices (Node ts)
= concatMap (getIndices . snd) ts
partitions :: Eq a => [a] -> [a] -> ([a], [a], [a])
partitions str1 str2
= partition' ([], str1, str2)
where
partition' :: Eq a => ([a], [a], [a]) -> ([a], [a], [a])
partition' (pfix, (s : str1), (s' : str2))
| s == s' = partition' ((s : pfix), str1, str2)
| otherwise = (reverse pfix, (s : str1), (s' : str2))
partition' (pfix, str1, str2)
= (pfix, str1, str2)
findSubstrings' :: String -> SuffixTree -> [Int]
findSubstrings' [] (Leaf n)
= [n]
findSubstrings' str (Leaf n)
= []
findSubstrings' str (Node [])
= []
findSubstrings' str (Node ((s, st) : ts))
| null str' = getIndices st
| null sub = findSubstrings' str' st
| otherwise = findSubstrings' str (Node ts)
where
(p, str', sub) = partitions str s
------------------------------------------------------
insert' :: (String, Int) -> SuffixTree -> SuffixTree
insert' (str, n) (Node [])
= Node [(str, Leaf n)]
insert' (str, n) (Node ((s, st) : ts))
| null p = Node ((s, st) : ts')
| p == s = Node ((s, insert' (str', n) st) : ts)
| otherwise = Node ((p, Node [(str', Leaf n), (s', st)]) : ts)
where
(p, str', s') = partitions str s
Node ts' = insert' (str, n) (Node ts)
-- This function is given
buildTree :: String -> SuffixTree
buildTree s
= foldl (flip insert') (Node []) (zip (suffixes s) [0..length s-1])
------------------------------------------------------
-- Part IV
longestRepeatedSubstring :: SuffixTree -> String
longestRepeatedSubstring
= undefined
------------------------------------------------------
-- Example strings and suffix trees...
s1 :: String
s1
= "banana"
s2 :: String
s2
= "mississippi"
t1 :: SuffixTree
t1
= Node [("banana", Leaf 0),
("a", Node [("na", Node [("na", Leaf 1),
("", Leaf 3)]),
("", Leaf 5)]),
("na", Node [("na", Leaf 2),
("", Leaf 4)])]
t2 :: SuffixTree
t2
= Node [("mississippi", Leaf 0),
("i", Node [("ssi", Node [("ssippi", Leaf 1),
("ppi", Leaf 4)]),
("ppi", Leaf 7),
("", Leaf 10)]),
("s", Node [("si", Node [("ssippi", Leaf 2),
("ppi", Leaf 5)]),
("i", Node [("ssippi", Leaf 3),
("ppi", Leaf 6)])]),
("p", Node [("pi", Leaf 8),
("i", Leaf 9)])]
module PTI where
import Data.Maybe
data Expr = Number Int |
Boolean Bool |
Id String |
Prim String |
Cond Expr Expr Expr |
App Expr Expr |
Fun String Expr
deriving (Eq, Show)
data Type = TInt |
TBool |
TFun Type Type |
TVar String |
TErr
deriving (Eq, Show)
showT :: Type -> String
showT TInt
= "Int"
showT TBool
= "Bool"
showT (TFun t t')
= "(" ++ showT t ++ " -> " ++ showT t' ++ ")"
showT (TVar a)
= a
showT TErr
= "Type error"
type TypeTable = [(String, Type)]
type TEnv
= TypeTable -- i.e. [(String, Type)]
type Sub
= TypeTable -- i.e. [(String, Type)]
-- Built-in function types...
primTypes :: TypeTable
primTypes
= [("+", TFun TInt (TFun TInt TInt)),
(">", TFun TInt (TFun TInt TBool)),
("==", TFun TInt (TFun TInt TBool)),
("not", TFun TBool TBool)]
------------------------------------------------------
-- PART I
-- Pre: The search item is in the table
lookUp :: Eq a => a -> [(a, b)] -> b
lookUp key dict
= tryToLookUp key undefined dict
tryToLookUp :: Eq a => a -> b -> [(a, b)] -> b
tryToLookUp _ def []
= def
tryToLookUp x def ((key, value):dict)
| x == key = value
| otherwise = tryToLookUp x def dict
-- Pre: The given value is in the table
reverseLookUp :: Eq b => b -> [(a, b)] -> [a]
reverseLookUp value dict
= map fst . filter f $ dict
where
f x = snd x == value
occurs :: String -> Type -> Bool
occurs s (TVar ident)
= s == ident
occurs s (TFun t t')
= occurs s t || occurs s t'
occurs _ _
= False
------------------------------------------------------
-- PART II
-- Pre: There are no user-defined functions (constructor Fun)
-- Pre: All type variables in the expression have a binding in the given
-- type environment
inferType :: Expr -> TEnv -> Type
inferType (Number _) _
= TInt
inferType (Boolean _) _
= TBool
inferType (Id ident) tenv
= lookUp ident tenv
inferType (Prim ident) _
= lookUp ident primTypes
inferType (Cond c t f) tenv
| infer c /= TBool = TErr
| tType == fType = tType
| otherwise = TErr
where
infer e = inferType e tenv
tType = infer t
fType = infer f
inferType (App f a) tenv
| not . isTFun $ fType = TErr
| fArg == aType = fOut
| otherwise = TErr
where
infer e = inferType e tenv
fType = infer f
aType = infer a
(TFun fArg fOut) = fType
isTFun :: Type -> Bool
isTFun (TFun _ _)
= True
isTFun _
= False
------------------------------------------------------
-- PART III
applySub
= undefined
unify :: Type -> Type -> Maybe Sub
unify t t'
= unifyPairs [(t, t')] []
unifyPairs :: [(Type, Type)] -> Sub -> Maybe Sub
unifyPairs
= undefined
------------------------------------------------------
-- PART IV
updateTEnv :: TEnv -> Sub -> TEnv
updateTEnv tenv tsub
= map modify tenv
where
modify (v, t) = (v, applySub tsub t)
combine :: Sub -> Sub -> Sub
combine sNew sOld
= sNew ++ updateTEnv sOld sNew
-- In combineSubs [s1, s2,..., sn], s1 should be the *most recent* substitution
-- and will be applied *last*
combineSubs :: [Sub] -> Sub
combineSubs
= foldr1 combine
inferPolyType :: Expr -> Type
inferPolyType
= undefined
-- You may optionally wish to use one of the following helper function declarations
-- as suggested in the specification.
-- inferPolyType' :: Expr -> TEnv -> [String] -> (Sub, Type, [String])
-- inferPolyType'
-- = undefined
-- inferPolyType' :: Expr -> TEnv -> Int -> (Sub, Type, Int)
-- inferPolyType'
-- = undefined
------------------------------------------------------
-- Monomorphic type inference test cases from Table 1...
env :: TEnv
env = [("x",TInt),("y",TInt),("b",TBool),("c",TBool)]
ex1, ex2, ex3, ex4, ex5, ex6, ex7, ex8 :: Expr
type1, type2, type3, type4, type5, type6, type7, type8 :: Type
ex1 = Number 9
type1 = TInt
ex2 = Boolean False
type2 = TBool
ex3 = Prim "not"
type3 = TFun TBool TBool
ex4 = App (Prim "not") (Boolean True)
type4 = TBool
ex5 = App (Prim ">") (Number 0)
type5 = TFun TInt TBool
ex6 = App (App (Prim "+") (Boolean True)) (Number 5)
type6 = TErr
ex7 = Cond (Boolean True) (Boolean False) (Id "c")
type7 = TBool
ex8 = Cond (App (Prim "==") (Number 4)) (Id "b") (Id "c")
type8 = TErr
------------------------------------------------------
-- Unification test cases from Table 2...
u1a, u1b, u2a, u2b, u3a, u3b, u4a, u4b, u5a, u5b, u6a, u6b :: Type
sub1, sub2, sub3, sub4, sub5, sub6 :: Maybe Sub
u1a = TFun (TVar "a") TInt
u1b = TVar "b"
sub1 = Just [("b",TFun (TVar "a") TInt)]
u2a = TFun TBool TBool
u2b = TFun TBool TBool
sub2 = Just []
u3a = TFun (TVar "a") TInt
u3b = TFun TBool TInt
sub3 = Just [("a",TBool)]
u4a = TBool
u4b = TFun TInt TBool
sub4 = Nothing
u5a = TFun (TVar "a") TInt
u5b = TFun TBool (TVar "b")
sub5 = Just [("b",TInt),("a",TBool)]
u6a = TFun (TVar "a") (TVar "a")
u6b = TVar "a"
sub6 = Nothing
------------------------------------------------------
-- Polymorphic type inference test cases from Table 3...
ex9, ex10, ex11, ex12, ex13, ex14 :: Expr
type9, type10, type11, type12, type13, type14 :: Type
ex9 = Fun "x" (Boolean True)
type9 = TFun (TVar "a1") TBool
ex10 = Fun "x" (Id "x")
type10 = TFun (TVar "a1") (TVar "a1")
ex11 = Fun "x" (App (Prim "not") (Id "x"))
type11 = TFun TBool TBool
ex12 = Fun "x" (Fun "y" (App (Id "y") (Id "x")))
type12 = TFun (TVar "a1") (TFun (TFun (TVar "a1") (TVar "a3")) (TVar "a3"))
ex13 = Fun "x" (Fun "y" (App (App (Id "y") (Id "x")) (Number 7)))
type13 = TFun (TVar "a1") (TFun (TFun (TVar "a1") (TFun TInt (TVar "a3")))
(TVar "a3"))
ex14 = Fun "x" (Fun "y" (App (Id "x") (Prim "+")))
type14 = TFun (TFun (TFun TInt (TFun TInt TInt)) (TVar "a3"))
(TFun (TVar "a2") (TVar "a3"))
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment