Skip to content

Instantly share code, notes, and snippets.

@benperez
Last active September 17, 2015 02:43
Show Gist options
  • Save benperez/3cfc588e2f19ed50e52b to your computer and use it in GitHub Desktop.
Save benperez/3cfc588e2f19ed50e52b to your computer and use it in GitHub Desktop.
Haskell Recipes
import Control.Applicative ((<$>), (<*>))
-- Binary Search
-- find the index of the given integer in the given sorted list
binsearch :: Int -> [Int] -> Maybe Int
binsearch _ [] = Nothing
binsearch v l = case v `compare` middleValue of
EQ -> Just middleIndex
GT -> (+) <$> Just (middleIndex + 1) <*> binsearch v (take middleIndex l)
LT -> binsearch v $ drop (middleIndex + 1) l
where
middleIndex = quot (length l) 2
middleValue = l !! middleIndex
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment