Skip to content

Instantly share code, notes, and snippets.

@samidarko
Created March 8, 2018 10:06
Show Gist options
  • Save samidarko/221e6426d6a498e9116d80271af881ad to your computer and use it in GitHub Desktop.
Save samidarko/221e6426d6a498e9116d80271af881ad to your computer and use it in GitHub Desktop.
binary search function in Haskell for Int lists
binarySearch :: Ord a => a -> [a] -> Maybe Int
binarySearch s xs = let left = 0
right = length xs - 1
in fn left right
where fn l r = if l > r
then Nothing
else let m = (l + r) `div` 2
e = xs !! m
in if e < s
then fn (m+1) r
else if e > s
then fn l (m-1)
else Just m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment