1

Possible Duplicate:
Pattern matching variables in a case statement in Haskell

I have the following simplified code (the actual code does implement something meaningful ):

import Data.Char
import Data.Maybe
import Control.Monad
import Control.Applicative

testA :: [Int] -> Maybe Int -> Maybe Int
testA [] _       = Nothing
testA _  Nothing = Nothing
testA (x:xs) v = case x of
  1         -> (+) <$> v <*> return x
  otherwise -> testA xs v

testB :: (MonadPlus m, Applicative m) => [Int] -> m Int -> m Int
testB [] _     = mzero
testB _  mzero = mzero
testB (x:xs) v = case x of
  1         -> (+) <$> v <*> return x
  otherwise -> testB xs v

main = do
  let xpto = testA [1,2,3,1,5] (Just 5)
  print xpto
  let ypto = testB [1,2,3,1,5] (Just 5)
  print ypto

It is my understanding that testA and testB should behave the same when feed with the Maybe Monad, meaning that mzero should translate to Nothing.

However, in test B ghc actually gives a warning:

Pattern match(es) are overlapped
In an equation for `testB': testB (x : xs) v = ..

And the output is different:

Just 6 (correct)
Just 5 (incorrect)

I am not sure what I might be missing, why isn't the mzero equivalent to nothing in the pattern match?

Community
  • 1
  • 1
jcristovao
  • 554
  • 2
  • 12
  • You're right... I actually saw that explanation in RWH, but I thought it only applied to case. The actual solution is to use guards, and eliminate the mzero. – jcristovao Feb 05 '13 at 11:57

0 Answers0