1
\$\begingroup\$

I just learned about Maybe in Haskell, so I decided to try to use it with a binary search.

Here's the function:

binarySearch :: (Ord a, Int b) => [a] -> a -> b -> b -> Maybe b
binarySearch l e beg last
 | lookat < e = (binarySearch l e i last)
 | lookat > e = (binarySearch l e beg i)
 | lookat == e = Just i
 | otherwise = Nothing
 where i = floor ((beg+last)/2)
 lookat = l !! i

l is a list, e is the element of interest, beg is the start of the section of interest and end is the end of said section. The error I am getting is:

BinarySearch.hs:1:25:
 `Int' is applied to too many type arguments
 In the type signature for `binarySearch':
 binarySearch :: (Ord a, Int b) => [a] -> a -> b -> b -> Maybe b

I have tried a few other things including:

binarySearch :: Ord a => [a] -> a -> Int -> Int -> Maybe b

Yielding the error:

BinarySearch.hs:6:23:
 Could not deduce (b ~ Int)
 from the context (Ord a)
 bound by the type signature for
 binarySearch :: Ord a => [a] -> a -> Int -> Int -> Maybe b
 at BinarySearch.hs:(3,1)-(9,22)
 `b' is a rigid type variable bound by
 the type signature for
 binarySearch :: Ord a => [a] -> a -> Int -> Int -> Maybe b
 at BinarySearch.hs:3:1
 In the first argument of `Just', namely `i'
 In the expression: Just i
 In an equation for `binarySearch':
 binarySearch l e beg last
 | lookat < e = (binarySearch l e i last)
 | lookat > e = (binarySearch l e beg i)
 | lookat == e = Just i
 | otherwise = Nothing
 where
 i = floor ((beg + last) / 2)
 lookat = l !! i

I am not sure what I am doing wrong. Any corrections or comments on style or solution would be highly appreciated.

asked Dec 19, 2012 at 22:28
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You don't want Int b, you just want Int:

Ord a => [a] -> a -> Int -> Int -> Maybe Int
answered Dec 19, 2012 at 22:56
\$\endgroup\$
1
  • \$\begingroup\$ Thank you! To make it fully work I also had to get rid of float and use quot instead of / when calculating i \$\endgroup\$ Commented Dec 19, 2012 at 23:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.