Вопрос

Here is my first code

maybe_devide :: Maybe Integer -> Maybe Integer -> Maybe Integer
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

And the error message for code 1 is shown below:

[1 of 1] Compiling Main             ( test2.hs, interpreted )

test2.hs:1:246: parse error on input `->'
Failed, modules loaded: none.

Here is the second code written by my friend Bryan Olivier:

maybe_devide :: Maybe Integer -> Maybe Integer -> Maybe Integer
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

However the error message is different this time:

Warning: Pattern match(es) are non-exhaustive
         In a case alternative:
             Patterns not matched:
                 (Nothing, Nothing)
                 (Just _, Just _)

test.hs:7:18: Warning: Defined but not used: `y'

test.hs:8:9: Warning: Defined but not used: `x'
Ok, modules loaded: Main.
*Main> 
Это было полезно?

Решение

I was actually able to compile both of these snippets in ghci (version 7.4.2). Something to look out for is using tabs instead of spaces (which could have been lost upon pasting into SO and formatting).

The messages appearing in your second snippet are just compiler warnings. You could clean up your code a little by using the built in pattern matching instead of a case. Here is an equivalent function:

divide :: Maybe Integer -> Maybe Integer -> Maybe Integer
divide (Just x) (Just y)
    | y == 0 = Nothing
    | otherwise = Just (div x y)
divide _ _ = Nothing

Другие советы

Your first error is at line 1, character 246, suggesting that you lost all formatting before compilation.

Your compiler is more picky then mine, but you are clearly missing the (Nothing,Nothing) case. The (Just _, Just _) case I can only explain as you are also missing the guard | x== 0 && y == 0, but I'm not sure of that.

EDIT: I reproduced the warnings using -Wall on ghc and the missing guard is not getting rid of this warning. Maybe someone else can explain that one.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top