September 2017 Update
This commit is contained in:
parent
bba7bfd280
commit
ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions
|
|
@ -1,9 +0,0 @@
|
|||
binarySearch :: Integral a => (a -> Ordering) -> (a, a) -> Maybe a
|
||||
binarySearch p (low,high)
|
||||
| high < low = Nothing
|
||||
| otherwise =
|
||||
let mid = (low + high) `div` 2 in
|
||||
case p mid of
|
||||
LT -> binarySearch p (low, mid-1)
|
||||
GT -> binarySearch p (mid+1, high)
|
||||
EQ -> Just mid
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
import Data.Array
|
||||
|
||||
binarySearchArray :: (Ix i, Integral i, Ord e) => Array i e -> e -> Maybe i
|
||||
binarySearchArray a x = binarySearch p (bounds a) where
|
||||
p m = x `compare` (a ! m)
|
||||
52
Task/Binary-search/Haskell/binary-search.hs
Normal file
52
Task/Binary-search/Haskell/binary-search.hs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import Data.Array (Array, Ix, (!), listArray, bounds)
|
||||
|
||||
-- BINARY SEARCH --------------------------------------------------------------
|
||||
bSearch
|
||||
:: Integral a
|
||||
=> (a -> Ordering) -> (a, a) -> Maybe a
|
||||
bSearch p (low, high)
|
||||
| high < low = Nothing
|
||||
| otherwise =
|
||||
let mid = (low + high) `div` 2
|
||||
in case p mid of
|
||||
LT -> bSearch p (low, mid - 1)
|
||||
GT -> bSearch p (mid + 1, high)
|
||||
EQ -> Just mid
|
||||
|
||||
-- Application to an array:
|
||||
bSearchArray
|
||||
:: (Ix i, Integral i, Ord e)
|
||||
=> Array i e -> e -> Maybe i
|
||||
bSearchArray a x = bSearch (compare x . (a !)) (bounds a)
|
||||
|
||||
-- TEST -----------------------------------------------------------------------
|
||||
axs
|
||||
:: (Num i, Ix i)
|
||||
=> Array i String
|
||||
axs =
|
||||
listArray
|
||||
(0, 11)
|
||||
[ "alpha"
|
||||
, "beta"
|
||||
, "delta"
|
||||
, "epsilon"
|
||||
, "eta"
|
||||
, "gamma"
|
||||
, "iota"
|
||||
, "kappa"
|
||||
, "lambda"
|
||||
, "mu"
|
||||
, "theta"
|
||||
, "zeta"
|
||||
]
|
||||
|
||||
main :: IO ()
|
||||
main =
|
||||
let e = "mu"
|
||||
found = bSearchArray axs e
|
||||
in putStrLn $
|
||||
'\'' :
|
||||
e ++
|
||||
case found of
|
||||
Nothing -> "' Not found"
|
||||
Just x -> "' found at index " ++ show x
|
||||
Loading…
Add table
Add a link
Reference in a new issue