Last active
September 17, 2015 02:43
-
-
Save benperez/3cfc588e2f19ed50e52b to your computer and use it in GitHub Desktop.
Haskell Recipes
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
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