Last active
March 24, 2022 11:41
-
-
Save evgenii-malov/d286528737dd4ccd0b20e2eda16a6dc8 to your computer and use it in GitHub Desktop.
binary search on a list and BST with Haskell
This file contains hidden or 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
-- GHCi, version 8.8.4 | |
-- explain video https://www.youtube.com/watch?v=LxbJS9L531g&t=798s | |
import Data.Maybe | |
import PrettyT | |
-- data Btree a = Empty | Node a (Btree a) (Btree a) deriving Show | |
data LR = Lm | Rm deriving Eq | |
b :: Ord a => [a] -> a -> LR -> Maybe Int | |
b [] _ _ = Nothing | |
b xs e lr = go Nothing 0 xs where | |
go c _ [] = c | |
go c cb [a] = if a == e then Just cb else c | |
go c cb x | (me == e) && (lr == Rm) = go (Just $ cb+mi) (cb+(length xl)+1) xr | |
| (me == e) && (lr == Lm) = go (Just $ cb+mi) cb xl | |
| e > me = go c (cb+(length xl)+1) xr | |
| e < me = go c cb xl | |
where | |
(xl,(me:xr)) = splitAt mi x | |
mi = ((length x) `div` 2) | |
data D = L | R deriving Show | |
-- binary search in a BST | |
bs :: Ord a => Btree a -> a -> Maybe [D] | |
bs t e = reverse <$> go [] t where | |
go f Empty = Nothing | |
go f (Node a l r) | a == e = Just $ f | |
| e > a = go (R:f) r | |
| e < a = go (L:f) l | |
build :: Ord a => [a] -> Btree a | |
build l = foldr ins Empty l | |
ins :: Ord a => a -> Btree a -> Btree a | |
ins e Empty = Node e Empty Empty | |
ins e (Node a l r) | e >= a = Node a l (ins e r) | |
| e < a = Node a (ins e l) r | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
explain video https://www.youtube.com/watch?v=LxbJS9L531g&t=798s