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.

\$\endgroup\$
2
\$\begingroup\$

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

Ord a => [a] -> a -> Int -> Int -> Maybe Int
\$\endgroup\$
  • \$\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\$ – mjgpy3 Dec 19 '12 at 23:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.