Skip to content
Snippets Groups Projects
Commit 94a623c9 authored by ik1g19's avatar ik1g19
Browse files

add sheets

parents
No related branches found
No related tags found
No related merge requests found
import Debug.Trace
amSplit :: (Ord a, Show a) => [a] -> [[a]]
amSplit [] = []
amSplit xs = build [] [] xs
where
antiMonotone :: (Ord a, Show a) => [a] -> Bool
antiMonotone ls = (antiMonotoneAsc ls) || (antiMonotoneDesc ls)
where
antiMonotoneAsc :: (Ord a, Show a) => [a] -> Bool
antiMonotoneAsc [c] = True
antiMonotoneAsc (c:cs) | head cs == c = antiMonotoneAsc cs
| head cs > c = antiMonotoneDesc cs
| otherwise = False
antiMonotoneDesc :: (Ord a, Show a) => [a] -> Bool
antiMonotoneDesc [c] = True
antiMonotoneDesc (c:cs) | head cs == c = antiMonotoneDesc cs
| head cs < c = antiMonotoneAsc cs
| otherwise = False
--accss is the accumulated list of anti monotone lists
--cs is the current list that is anti monotone
--d:ds is the list that is being searched
build :: (Ord a, Show a) => [[a]] -> [a] -> [a] -> [[a]]
build accss cs [] = accss ++ [cs]
build accss cs (d:ds) | antiMonotone (cs ++ [d]) == True = build accss (cs ++ [d]) ds
| otherwise = build (accss ++ [cs]) [d] ds
\ No newline at end of file
all :: (a -> Bool) -> [a] -> Bool
all f xs = foldr (&&) True (map f xs)
any :: (a -> Bool) -> [a] -> Bool
any f xs = foldr (||) False (map f xs)
\ No newline at end of file
import Data.List
data Tree a = Leaf | Node (Tree a) a (Tree a) deriving Show
halve :: [a] -> ([a],a,[a])
halve xs = (take n xs, xs !! n, drop (n + 1) xs)
where n = length xs `div` 2
balance :: [a] -> Tree a
balance [] = Leaf
balance xs = Node (balance ls) x (balance rs)
where (ls, x, rs) = halve xs
toTree :: Ord a => [a] -> Tree a
toTree = balance . sort
\ No newline at end of file
--TEMPLATE FILE FOR COURSEWORK 1 for COMP2209
--Julian Rathke, Oct 2019
--EXERCISE A4 ONLY
--CONTAINS FUNCTION REQIURED FOR COMPILATION AGAINST THE TEST SUITE
--MODIFY THE FUNCTION DEFINITIONS WITH YOUR OWN SOLUTIONS
--IMPORTANT : DO NOT MODIFY ANY FUNCTION TYPES
module Exercises (neighbours) where
import Data.List
import Data.Ord
type Point a = (a,a)
type Metric a = (Point a) -> (Point a) -> Double
-- Exercise A4
neighbours :: Int -> Metric a -> Point a -> [Point a] -> [Point a]
neighbours k d p xs | k < 0 = error "k cannot be less than 0"
| otherwise = take k (sortBy (comparing (d p)) xs)
\ No newline at end of file
--TEMPLATE FILE FOR COURSEWORK 1 for COMP2209
--Julian Rathke, Oct 2019
--EXERCISE A5 ONLY
--CONTAINS FUNCTION REQIURED FOR COMPILATION AGAINST THE TEST SUITE
--MODIFY THE FUNCTION DEFINITIONS WITH YOUR OWN SOLUTIONS
--IMPORTANT : DO NOT MODIFY ANY FUNCTION TYPES
module Exercises (findBonding) where
-- Exercise A5
import Data.Maybe
data MTree a = RootNode [MTree a] | Node a [MTree a] deriving Show
--parameters are pair, number child took (1 indexed), list of other children
data Direction a = Children a Int [MTree a] | Root Int [MTree a] deriving Show
type Trail a = [Direction a]
type Zipper a = (MTree a, Trail a)
findBonding :: Eq a => (a -> a -> Bool) -> [a] -> Maybe [(a,a)]
findBonding p [] = Just []
findBonding p xs | odd $ length xs = Nothing
| otherwise = findBonds zipper
where
tree = buildTree xs p
zipper = (tree,[])
solutionDepth = ((length xs) `div` 2)
fsn :: Zipper (a,a) -> Maybe (Zipper (a,a))
fsn = findSoltNode solutionDepth 0 1
findBonds :: Zipper (a,a) -> Maybe [(a,a)]
findBonds z = (dupeReversePath . findSoltPath . fsn) z
buildTree :: [a] -> (a -> a -> Bool) -> MTree (a,a)
buildTree xs p = RootNode (generateChildren xs [] p)
--xs is the list of values that can be used for this row
--ys is the list of values that can be used by the children
--p is the predicate
--(x1:x2:[]) [] is for when all pairs have been made along this branch
--(x1:x2:[]) ys is for when all pairs have been made along this row
generateChildren :: [a] -> [a] -> (a -> a -> Bool) -> [MTree (a,a)]
generateChildren (x1:x2:[]) [] p | p x1 x2 && p x2 x1 = Node (x1,x2) [] : []
| otherwise = []
generateChildren (x1:x2:[]) ys p | p x1 x2 && p x2 x1 = Node (x1,x2) (generateChildren ys [] p) : []
| otherwise = []
generateChildren (x1:x2:xs) ys p | p x1 x2 && p x2 x1 = Node (x1,x2) (generateChildren (xs++ys) [] p) : generateChildren (x1:xs) (x2:ys) p
| otherwise = generateChildren (x1:xs) (x2:ys) p
--searches the tree for a solution
--sd is solution depth
--d is current depth
--nc is the child to take
findSoltNode :: Int -> Int -> Int -> Zipper (a,a) -> Maybe (Zipper (a,a))
findSoltNode sd d nc z@(Node _ [],(Children _ c _) : ds) | sd == d = Just z
| otherwise = findSoltNode sd (d-1) (c+1) (goUp z)
findSoltNode sd d nc z@(Node _ ts,(Children _ c _) : ds) | sd == d = Just z
| (sd /= d) &&
(nc > length ts) = findSoltNode sd (d-1) (c+1) (goUp z)
| otherwise = findSoltNode sd (d+1) 1 (goChild z nc)
findSoltNode sd d nc z@(Node _ ts,(Root c _) : ds) | sd == d = Just z
| (sd /= d) &&
(nc > length ts) = findSoltNode sd (d-1) (c+1) (goUp z)
| otherwise = findSoltNode sd (d+1) 1 (goChild z nc)
findSoltNode sd d nc z@(RootNode ts,ds) | (nc > length ts) = Nothing
| otherwise = findSoltNode sd (d+1) 1 (goChild z nc)
consOnMaybe :: (a,a) -> Maybe [(a,a)] -> Maybe [(a,a)]
consOnMaybe _ Nothing = Nothing
consOnMaybe x (Just xs) = Just (x : xs)
findSoltPath :: Maybe (Zipper (a,a)) -> Maybe [(a,a)]
findSoltPath Nothing = Nothing
findSoltPath ( Just z@(Node x _,(Children _ _ _) : ds) ) = x `consOnMaybe` findSoltPath (goUpMaybe (Just z))
where
--travel up tree when given node may exist
goUpMaybe :: Maybe (Zipper (a,a)) -> Maybe (Zipper (a,a))
goUpMaybe Nothing = Nothing
goUpMaybe ( Just (t,(Root c ts) : ds) ) = Just (RootNode (insertAt t ts c),[])
goUpMaybe ( Just (t,(Children x c ts) : ds) ) = Just (Node x (insertAt t ts c),ds)
findSoltPath ( Just z@(Node x _,(Root _ _) : ds) ) = Just (x : [])
dupeReversePath :: Maybe [(a,a)] -> Maybe [(a,a)]
dupeReversePath Nothing = Nothing
dupeReversePath ( Just ((x1,x2):[]) ) = (x1,x2) `consOnMaybe` Just ((x2,x1) : [])
dupeReversePath ( Just ((x1,x2):xs) ) = (x1,x2) `consOnMaybe` ((x2,x1) `consOnMaybe` (dupeReversePath (Just xs)))
--insert into index of a list
--1 indexed
insertAt :: a -> [a] -> Int -> [a]
insertAt x ys 1 = x:ys
insertAt x (y:ys) n = y:insertAt x ys (n-1)
--remove from index of a list
--0 indexed
deleteAt :: Int -> [a] -> [a]
deleteAt idx xs = lft ++ rgt
where (lft,(_:rgt)) = splitAt idx xs
--branch down child
goChild :: Zipper (a,a) -> Int -> Zipper (a,a)
goChild (RootNode ts,ds) c = ((ts!!(c-1),(Root c (deleteAt (c-1) ts)):ds))
goChild (Node x ts,ds) c = ((ts!!(c-1),(Children x c (deleteAt (c-1) ts)):ds))
--go up tree
goUp :: Zipper (a,a) -> Zipper (a,a)
goUp (t,(Root c ts) : ds) = (RootNode (insertAt t ts c),[])
goUp (t,(Children x c ts) : ds) = (Node x (insertAt t ts c),ds)
\ No newline at end of file
{-# LANGUAGE DeriveGeneric #-}
--TEMPLATE FILE FOR COURSEWORK 1 for COMP2209
--Julian Rathke, Oct 2019
--EXERCISE A6 ONLY
--CONTAINS FUNCTION REQIURED FOR COMPILATION AGAINST THE TEST SUITE
--MODIFY THE FUNCTION DEFINITIONS WITH YOUR OWN SOLUTIONS
--IMPORTANT : DO NOT MODIFY ANY FUNCTION TYPES
module Exercises (insertFromCurrentNode,VTree(..),Direction(..),Trail(..),Zipper(..)) where
-- The following two imports are needed for testing, do not delete
import GHC.Generics (Generic,Generic1)
import Control.DeepSeq
data VTree a = Leaf | Node (VTree a) a Int (VTree a) deriving (Eq,Show,Generic,Generic1)
data Direction a = L a Int (VTree a) | R a Int (VTree a) deriving (Eq,Show,Generic,Generic1)
type Trail a = [Direction a]
type Zipper a = (VTree a, Trail a)
instance NFData a => NFData (VTree a)
instance NFData a => NFData (Direction a)
-- Exercise A6
insertFromCurrentNode :: Ord a => a -> Zipper a -> Zipper a
insertFromCurrentNode v z@(Node l x c r,(L y _ _) : ts) | containsNode v (goRoot z) = goRoot z
| (v > x) && (v < y) = insertValue v (goUp z)
| otherwise = insertValue v (goRoot z)
insertFromCurrentNode v z@(Node l x c r,(R y _ _) : ts) | containsNode v (goRoot z) = goRoot z
| (v > y) && (v < x) = insertValue v (goUp z)
| otherwise = insertValue v (goRoot z)
insertFromCurrentNode v z | containsNode v (goRoot z) = goRoot z
| otherwise = insertValue v (goRoot z)
insertValue :: Ord a => a -> Zipper a -> Zipper a
insertValue v z@(Leaf,ts) = (Node Leaf v 1 Leaf,ts)
insertValue v z@(Node l x c r,ts) | v < x = insertValue v (goLeft z)
| otherwise = insertValue v (goRight z)
--travels to root of the tree
goRoot :: Ord a => Zipper a -> Zipper a
goRoot (t,[]) = (t,[])
goRoot z = goRoot (goUp z)
--increments the visit counter of a tree
incrCnt :: Ord a => Zipper a -> Zipper a
incrCnt (Node l v c r,ts) = (Node l v (c+1) r,ts)
incrCnt (Leaf,ts) = (Leaf,ts)
containsNode :: Ord a => a -> Zipper a -> Bool
containsNode _ (Leaf,_) = False
containsNode y (Node l x c r,_) | x < y = containsNode y (r,[])
| x > y = containsNode y (l,[])
| otherwise = True
goLeft,goRight,goUp :: Ord a => Zipper a -> Zipper a
goLeft (Node l x c r,ts) = incrCnt (l,(L x c r):ts)
goRight (Node l x c r,ts) = incrCnt (r,(R x c l):ts)
goUp (t,(L x c r) : ts) = incrCnt (Node t x c r,ts)
goUp (t,(R x c l) : ts) = incrCnt (Node l x c t,ts)
mkTree :: Ord a => [a] -> Zipper a
mkTree = foldl (\z -> \x -> insertFromCurrentNode x z) (Leaf,[])
\ No newline at end of file
data Expr = Var String | Lam String Expr | App Expr Expr | Cl (String Expr,Env) deriving (Eq,Show,Read)
type Env = [(String,Expr)]
lookupVar :: String -> Env -> Maybe Expr
lookupVar var env | lookup var env /= Nothing =
\ No newline at end of file
-- import Control.Exception
-- main = catch (print $ 5 `div` 0) handler
-- where
-- handler :: SomeException -> IO ()
-- handler ex = putStrLn $ "Caught exception: " ++ show ex
import qualified Control.Exception as Exc
{-# NOINLINE unsafeCleanup #-}
unsafeCleanup :: a -> Maybe a
unsafeCleanup x = unsafePerformIO $ Exc.catch (x `seq` return (Just x)) handler
where
handler exc = return Nothing `const` (exc :: Exc.ErrorCall)
\ No newline at end of file
{-# LANGUAGE DeriveGeneric #-}
--TEMPLATE FILE FOR COURSEWORK 1 for COMP2209
--Julian Rathke, Oct 2019
--EXERCISE A7 ONLY
--CONTAINS FUNCTION REQIURED FOR COMPILATION AGAINST THE TEST SUITE
--MODIFY THE FUNCTION DEFINITIONS WITH YOUR OWN SOLUTIONS
--IMPORTANT : DO NOT MODIFY ANY FUNCTION TYPES
module Exercises (evalInst,Instruction(..),Stack,SMProg) where
import GHC.Generics (Generic,Generic1)
import Control.DeepSeq
data Instruction = Add | Sub | Mul | Div | Dup | Pop deriving (Eq,Ord,Show,Generic)
type Stack = [Maybe Int]
type SMProg = [Instruction]
instance NFData (Instruction)
-- Exercise A7
evalInst :: Stack -> SMProg -> Stack
evalInst s p = last evals
where evals = iterateStack p s
iterateStack :: SMProg -> Stack -> [Stack]
iterateStack [] x = x : []
iterateStack (i:is) x = x : iterateStack is (step i x)
--performs one instruction on the stack and returns
--the resulting stack
step :: Instruction -> Stack -> Stack
step _ [] = error "Instruction applied to empty stack"
step Dup l@(x:xs) = x : l
step Pop (x:xs) = xs
step _ (x:[]) = error "Instruction is binary operator but only one value is on stack"
step _ (Nothing:x:xs) = Nothing : xs
step _ (x:Nothing:xs) = Nothing : xs
step Add ((Just x1):(Just x2):xs) = Just (x1 + x2) : xs
step Sub ((Just x1):(Just x2):xs) = Just (x1 - x2) : xs
step Mul ((Just x1):(Just x2):xs) = Just (x1 * x2) : xs
step Div ((Just x1):(Just 0):xs) = Nothing : xs
step Div ((Just x1):(Just x2):xs) = Just (x1 `div` x2) : xs
\ No newline at end of file
{-# LANGUAGE DeriveGeneric #-}
--TEMPLATE FILE FOR COURSEWORK 1 for COMP2209
--Julian Rathke, Oct 2019
--EXERCISE A8 ONLY
--CONTAINS FUNCTION REQIURED FOR COMPILATION AGAINST THE TEST SUITE
--MODIFY THE FUNCTION DEFINITIONS WITH YOUR OWN SOLUTIONS
--IMPORTANT : DO NOT MODIFY ANY FUNCTION TYPES
module Exercises (findMaxReducers,Instruction(..),Stack,SMProg) where
import GHC.Generics (Generic,Generic1)
import Control.DeepSeq
data Instruction = Add | Sub | Mul | Div | Dup | Pop deriving (Eq,Ord,Show,Generic)
type Stack = [Maybe Int]
type SMProg = [Instruction]
instance NFData (Instruction)
-- Exercise A8
findMaxReducers :: Stack -> [SMProg]
findMaxReducers [] = []
findMaxReducers (s:[]) = [[]]
findMaxReducers s = breakLists [dynamicSolve s] []
where
--splits a list of lists into two different lists if a list contains more than one element
--ps is previous elements
dupeLists :: [[a]] -> [[a]] -> [[[a]]]
dupeLists (x@(z:[]):[]) ps = [ps++[x]] --list contained no elements with more than one element
dupeLists (x@(z:[]):xs) ps = dupeLists xs (ps++[x]) --list contains one element
dupeLists ((z:zs):xs) ps = [ps++[[z]]++xs,ps++[zs]++xs] --list contains more than one element
breakLists :: [[[a]]] -> [[[a]]] -> [[a]]
breakLists [] ps = map fromSingletons ps
where
fromSingletons :: [[a]] -> [a]
fromSingletons x = map (\(z:[]) -> z) x
breakLists (x:xs) ps | sum (map length x) == length x = breakLists xs (ps++[x]) --if the list only contains singleton lists
| otherwise = breakLists (ps++(dupeLists x [])++xs) []
dynamicSolve :: Stack -> [[Instruction]]
dynamicSolve (s1:s2:[]) = instrs : []
where instrs = map snd (findMax (s1:s2:[]) [])
dynamicSolve (s1:s2:ss) = instrs : dynamicSolve (val ++ ss)
where
--optimal value
val = fst (head (findMax (s1:s2:[]) ss))
--possible instructions to obtain it
instrs = map snd (findMax (s1:s2:[]) ss)
--converts a list of maybe a to list of a
--ignores nothing values
maybeToList :: [Maybe a] -> [a]
maybeToList [] = []
maybeToList (Nothing:xs) = maybeToList xs
maybeToList (Just x:xs) = x : maybeToList xs
--finds the optimal value to obtain between two numbers given the remaining stack
--returns optimal value and operation
--s is the stack containing the two values to compare
--rs is the rest of the stack
findMax :: Stack -> Stack -> [(Stack,Instruction)]
findMax s rs | odd (length (filter (<0) (maybeToList rs))) --if odd number of negative numbers
= filter (\p -> (fstVal p) `elem` (maxAbs (map fstVal outputs))) outputs --in rest of stack,choose highest absolute value
| otherwise
= filter (\p -> fstVal p == maximum (map fstVal posOutputs)) posOutputs --otherwise, choose highest value
where
--produces a list of possible operations, ignore any that evaluate to Nothing
outputs :: [(Stack,Instruction)]
outputs = filter (\p -> fst p /= [Nothing]) [(evalInst s [Add],Add),
(evalInst s [Sub],Sub),
(evalInst s [Mul],Mul),
(evalInst s [Div],Div),
(evalInst s [Pop],Pop)]
--produces a list of outputs that evaluate to a positive answer
posOutputs = filter (\p -> (0<=) (fstVal p)) outputs
--extracts the value of the first elem of a outputs tuple
fstVal :: (Stack,Instruction) -> Int
fstVal ((Just z):[],_) = z
--takes a list of ints and returns the ints with the largest absolute value
maxAbs :: [Int] -> [Int]
maxAbs zs = map fst (filter (\p -> snd p == max) (zip zs (map abs zs)))
where max = maximum (map abs zs)
-- Exercise A7
evalInst :: Stack -> SMProg -> Stack
evalInst s p = last evals
where evals = iterateStack p s
iterateStack :: SMProg -> Stack -> [Stack]
iterateStack [] x = x : []
iterateStack (i:is) x = x : iterateStack is (step i x)
--performs one instruction on the stack and returns
--the resulting stack
step :: Instruction -> Stack -> Stack
step _ [] = error "Instruction applied to empty stack"
step Dup l@(x:xs) = x : l
step Pop (x:xs) = xs
step _ (x:[]) = error "Instruction is binary operator but only one value is on stack"
step _ (Nothing:x:xs) = Nothing : xs
step _ (x:Nothing:xs) = Nothing : xs
step Add ((Just x1):(Just x2):xs) = Just (x1 + x2) : xs
step Sub ((Just x1):(Just x2):xs) = Just (x1 - x2) : xs
step Mul ((Just x1):(Just x2):xs) = Just (x1 * x2) : xs
step Div ((Just x1):(Just 0):xs) = Nothing : xs
step Div ((Just x1):(Just x2):xs) = Just (x1 `div` x2) : xs
\ No newline at end of file
{-# LANGUAGE DeriveGeneric #-}
--TEMPLATE FILE FOR COURSEWORK 1 for COMP2209
--Julian Rathke, Oct 2019
--EXERCISE A9 ONLY
--CONTAINS FUNCTION REQIURED FOR COMPILATION AGAINST THE TEST SUITE
--MODIFY THE FUNCTION DEFINITIONS WITH YOUR OWN SOLUTIONS
--IMPORTANT : DO NOT MODIFY ANY FUNCTION TYPES
module Exercises (isPossiblePower,Instruction(..),Stack,SMProg) where
import GHC.Generics (Generic,Generic1)
import Control.DeepSeq
data Instruction = Add | Sub | Mul | Div | Dup | Pop deriving (Eq,Ord,Show,Generic)
type Stack = [Maybe Int]
type SMProg = [Instruction]
instance NFData (Instruction)
-- Exercise A9
isPossiblePower :: Int -> Int -> Bool
isPossiblePower k l | k < 0 || l < 0 = False
| otherwise = foldr (&&) True (map (check k l) [1..100])
check :: Int -> Int -> Int -> Bool
check k l x = recursiveCheck (x^k) l [Just x]
--t is the target
--l is the number of dups left
--s is the stack
recursiveCheck :: Int -> Int -> Stack -> Bool
recursiveCheck _ _ [] = False
recursiveCheck t 0 s | (Just t:[]) == s = True
| otherwise = recursiveCheck t 0 (evalInst s [Mul])
recursiveCheck t l s = recursiveCheck t l (evalInst s [Mul]) || recursiveCheck t (l-1) (evalInst s [Dup])
-- Exercise A7
evalInst :: Stack -> SMProg -> Stack
evalInst s p = last evals
where evals = iterateStack p s
iterateStack :: SMProg -> Stack -> [Stack]
iterateStack [] x = x : []
iterateStack (i:is) x = x : iterateStack is (step i x)
--performs one instruction on the stack and returns
--the resulting stack
step :: Instruction -> Stack -> Stack
step _ [] = []
step Dup l@(x:xs) = x : l
step Pop (x:xs) = xs
step _ (x:[]) = []
step _ (Nothing:x:xs) = Nothing : xs
step _ (x:Nothing:xs) = Nothing : xs
step Add ((Just x1):(Just x2):xs) = Just (x1 + x2) : xs
step Sub ((Just x1):(Just x2):xs) = Just (x1 - x2) : xs
step Mul ((Just x1):(Just x2):xs) = Just (x1 * x2) : xs
step Div ((Just x1):(Just 0):xs) = Nothing : xs
step Div ((Just x1):(Just x2):xs) = Just (x1 `div` x2) : xs
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment