Minor code cleanup on HW1.

This commit is contained in:
Danila Fedorin 2019-01-16 13:15:45 -08:00
parent 739ea0d1ad
commit dbd1e17b2a

View File

@ -29,7 +29,7 @@ treeFoldr f a (Node i l r) = treeFoldr f (f i (treeFoldr f a r)) l
-- | foldr for non-empty lists.
treeFoldr1 :: (Int -> Int -> Int) -> Tree -> Int
treeFoldr1 f (Leaf i) = i
treeFoldr1 _ (Leaf i) = i
treeFoldr1 f (Node i l r) = treeFoldr f (f i (treeFoldr1 f r)) l
-- | Left associative fold.
@ -39,7 +39,7 @@ treeFoldl f a (Node i l r) = treeFoldl f (f i (treeFoldl f a l)) r
-- | foldl for non-empty lists.
treeFoldl1 :: (Int -> Int -> Int) -> Tree -> Int
treeFoldl1 f (Leaf i) = i
treeFoldl1 _ (Leaf i) = i
treeFoldl1 f (Node i l r) = treeFoldl f (f i (treeFoldl1 f l)) r
-- | In-order traversal fold.
@ -54,7 +54,7 @@ treeFold f a (Node i l r) = f i $ treeFold f (treeFold f a r) l
--
-- >>> leftmost (Node 5 (Leaf 6) (Leaf 7))
-- 6
--
--
-- >>> leftmost t1
-- 4
--
@ -62,7 +62,7 @@ treeFold f a (Node i l r) = f i $ treeFold f (treeFold f a r) l
-- 1
--
leftmost :: Tree -> Int
leftmost = treeFoldr1 (\i _ -> i)
leftmost = treeFoldr1 const
-- | The integer at the right-most node of a binary tree.
--
@ -71,7 +71,7 @@ leftmost = treeFoldr1 (\i _ -> i)
--
-- >>> rightmost (Node 5 (Leaf 6) (Leaf 7))
-- 7
--
--
-- >>> rightmost t1
-- 9
--
@ -79,7 +79,7 @@ leftmost = treeFoldr1 (\i _ -> i)
-- 9
--
rightmost :: Tree -> Int
rightmost = treeFoldl1 (\i _ -> i)
rightmost = treeFoldl1 const
-- | Get the maximum integer from a binary tree.
--
@ -154,7 +154,7 @@ sumInts = treeFoldr1 (+)
--
-- >>> preorder t2
-- [6,2,1,4,3,5,8,7,9]
--
--
preorder :: Tree -> [ Int ]
preorder = treeFold (:) []
@ -171,7 +171,7 @@ preorder = treeFold (:) []
--
-- >>> inorder t2
-- [1,2,3,4,5,6,7,8,9]
--
--
inorder :: Tree -> [ Int ]
inorder = treeFoldr (:) []
@ -183,13 +183,13 @@ inorder = treeFoldr (:) []
--
-- >>> isBST (Node 5 (Leaf 6) (Leaf 7))
-- False
--
--
-- >>> isBST t1
-- False
--
-- >>> isBST t2
-- True
--
--
isBST :: Tree -> Bool
isBST (Leaf _) = True
isBST (Node i l r) = i >= value l && i <= value r && isBST l && isBST r
@ -212,6 +212,6 @@ isBST (Node i l r) = i >= value l && i <= value r && isBST l && isBST r
--
-- >>> inBST 10 t2
-- False
--
--
inBST :: Int -> Tree -> Bool
inBST i = treeFoldr (\v acc -> acc || (v == i)) False