Created
August 27, 2019 05:36
-
-
Save ChrisPenner/3aaf7cae15d9369a405c471e68831f04 to your computer and use it in GitHub Desktop.
Binary tree search using lenses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Define a simple binary tree | |
data BT a | |
= BT { _leftTree :: BT a | |
, _val :: a | |
, _rightTree :: BT a | |
} | |
| Leaf | |
deriving (Show, Eq, Functor, Foldable, Traversable) | |
-- Generate traversals for the (partial) fields | |
makeLenses ''BT | |
-- Branch into one traversal or the other based on a predicate | |
branchBy :: (a -> Bool) -> Traversal' a b -> Traversal' a b -> Traversal' a b | |
branchBy p ta tb f s = | |
if p s then ta f s | |
else tb f s | |
-- Look for an element in a binary tree | |
binSearch :: Int -> BT Int -> Bool | |
binSearch n = has (deepOf (branchBy (anyOf val (> n)) leftTree rightTree) (val . only n)) | |
-- 4 | |
-- / \ | |
-- / \ | |
-- 2 7 | |
-- \ / | |
-- 3 6 | |
tree :: BT Int | |
tree = | |
BT (BT Leaf 2 (BT Leaf 3 Leaf)) | |
4 | |
(BT (BT Leaf 6 Leaf) 7 Leaf) | |
>>> binSearch 2 tree | |
True | |
>>> binSearch 3 tree | |
True | |
>>> binSearch 6 tree | |
True | |
>>> binSearch 20 tree | |
False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment