0

Just a simple question that i cannot solve I was trying to get maybe_divide by the following code as assignment required, however terminal give me an error message

test2.hs:1:112: Parse error in pattern: (Just x)

maybe_devide :: Maybe Float -> Maybe Float -> Maybe Float
maybe_devide maybeX maybeY = case maybeX maybeY of
  (Just x) (Just y)
    |x/=0 && y/=0 -> Just (div x y)
    |x=0 && y/=0  -> Just 0
    |x/=0 && y=0  -> Nothing
  Nothing (Just y) -> Nothing
  (Just x) Nothing -> Nothing

Who likes to tell me what is wrong with it? Thanks

4

1 回答 1

4

maybeX maybeY is applying the function maybeX on the argument maybeY, whereas you are intending to do case analysis on the the pair (maybeX,maybeY). Also you should use == for equality and not a single =. The following will do what you intend:

maybe_devide :: Maybe Float -> Maybe Float -> Maybe Float
maybe_devide maybeX maybeY = case (maybeX,maybeY) of
  (Just x,Just y)
    |x/=0 && y/=0 -> Just (div x y)
    |x==0 && y/=0  -> Just 0
    |x/=0 && y==0  -> Nothing
  (Nothing,Just y) -> Nothing
  (Just x,Nothing) -> Nothing

Alternatively you could make use of the Maybe monad, as in

maybe_devide :: Maybe Float -> Maybe Float -> Maybe Float
maybe_devide maybeX maybeY = do
        x <- maybeX
        y <- maybeY
        case (x,y) of
                (0,y) -> Just 0
                (x,0) -> Nothing
                (x,y) -> Just (div x y)
于 2013-03-31T00:43:44.477 回答