I struggle to understand how this binary-search function works:
bsearch :: Ord a => [a] -> a -> Bool
bsearch [] _ = False
bsearch xs x =
if x < y then bsearch ys1 x
else if x > y then bsearch ys2 x
else True
where
ys1 = take l xs
(y:ys2) = drop l xs
l = length xs `div` 2
I tried to think it by an example: bsearch [1,2,3,4] 4
but I don't understand where the function starts. I like to believe first l = length xs 'div' 2
gets calculated. l = 2
is the result.
Now I put my variables in (y:ys2) = drop l xs
where (y:ys2) = 3:[4]
which equals to drop 2 [1,2,3,4] = [3,4]
. Next else if 4 > 3 then bsearch ys2 x
gets executed where ys2 = [4]
and x = 4
. What happens next? How does x = 4
and ys2 = [4]
get compared?
EDIT: I think since bsearch [4] 4
is the new bsearch xs x
the new l = length xs 'div' 2 = length [4] 'div' 2 = 0
that executes drop 0 [4] = [4] = (4:[])
. 4 < 4
and 4 > 4
is False
therefore else True
.
Is this the way this function executes for my example?
I would be very happy if someone could help me with this function.