1

这是我的第一个代码

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

代码 1 的错误消息如下所示:

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

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

这是我的朋友 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

但是,这次的错误信息有所不同:

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> 
4

3 回答 3

6

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
于 2013-03-31T01:55:28.347 回答
2

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

于 2013-03-31T03:11:45.563 回答
1

你的编译器比我的更挑剔,但你显然错过了这个(Nothing,Nothing)案例。(Just _, Just _)我只能解释这个案子,因为你也错过了警卫| x== 0 && y == 0,但我不确定。

-Wall编辑:我使用on复制了警告,ghc而缺少的警卫并没有摆脱这个警告。也许其他人可以解释这一点。

于 2013-03-31T01:37:51.847 回答