Compare commits

...

2 Commits

Author SHA1 Message Date
Danila Fedorin d378cc4525 Clean up HW2 code. 2019-01-22 13:48:57 -08:00
Danila Fedorin eb8754f62d Clean up HW1 code. 2019-01-22 13:48:50 -08:00
2 changed files with 8 additions and 8 deletions

View File

@ -10,7 +10,7 @@ data Tree
-- | An example binary tree, which will be used in tests. -- | An example binary tree, which will be used in tests.
t1 :: Tree t1 :: Tree
t1 = Node 1 (Node 2 (Node 3 (Leaf 4) (Leaf 5)) t1 = Node 1 (Node 2 (Node 3 (Leaf 4) (Lea 5))
(Leaf 6)) (Leaf 6))
(Node 7 (Leaf 8) (Leaf 9)) (Node 7 (Leaf 8) (Leaf 9))
@ -62,7 +62,7 @@ treeFold f a (Node i l r) = f i $ treeFold f (treeFold f a r) l
-- 1 -- 1
-- --
leftmost :: Tree -> Int leftmost :: Tree -> Int
leftmost = treeFoldr1 const leftmost = treeFoldr1 (\a _ -> a)
-- | The integer at the right-most node of a binary tree. -- | The integer at the right-most node of a binary tree.
-- --
@ -79,7 +79,7 @@ leftmost = treeFoldr1 const
-- 9 -- 9
-- --
rightmost :: Tree -> Int rightmost :: Tree -> Int
rightmost = treeFoldl1 const rightmost = treeFoldl1 (\a _ -> a)
-- | Get the maximum integer from a binary tree. -- | Get the maximum integer from a binary tree.
-- --

View File

@ -32,7 +32,7 @@ instance Functor Tree where
-- | Map a function over a tree. Applies the given function to every label -- | Map a function over a tree. Applies the given function to every label
-- in the tree, preserving the tree's structure. -- in the tree, preserving the tree's structure.
-- --
-- >>> mapTree odd End -- >>> mapTree odd End
-- End -- End
-- --
@ -92,12 +92,12 @@ valueAt (x:xs) (Node a l r) = valueAt xs $ if x == L then l else r
-- >>> pathTo 10 ex -- >>> pathTo 10 ex
-- Nothing -- Nothing
-- --
pathTo :: Eq a => a -> Tree a -> Maybe Path pathTo :: Eq a => a -> Tree a -> Maybe Path
pathTo v End = Nothing pathTo v End = Nothing
pathTo v (Node a l r) = orElse currentNode $ orElse (pathHelper v l L) $ pathHelper v r R pathTo v (Node a l r) = orElse currentNode $ orElse (pathHelper v l L) $ pathHelper v r R
where where
currentNode = if a == v then Just [] else Nothing currentNode = if a == v then Just [] else Nothing
pathHelper v tree dir = (pathTo v tree) >>= (Just . (dir:)) pathHelper v tree dir = fmap (dir:) (pathTo v tree)
orElse m1 m2 = case m1 of orElse m1 m2 = if isJust m1 then m1 else m2
Just _ -> m1 isJust mx = mx /= Nothing
Nothing -> m2