Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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

Ord a => [a] -> a -> Int -> Int -> Maybe Int
share|improve this answer
    
Thank you! To make it fully work I also had to get rid of float and use quot instead of / when calculating i –  mjgpy3 Dec 19 '12 at 23:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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