2013-03-31 23 views
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> 

回答

6

我實際上能夠在ghci(版本7.4.2)中編譯這兩個片段。需要注意的是使用製表符而不是空格(粘貼到SO和格式化時可能會丟失)。

出現在您的第二個片段中的消息只是編譯器警告。您可以使用內置的模式匹配而不是case來清理代碼。下面是一個等價功能:

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

Thx男人,我們的代碼是完美的XD – libra

1

你的編譯器是比較挑剔然後我的,但你顯然缺少(Nothing,Nothing)情況。 (Just _, Just _)的情況我只能解釋,因爲你也錯過了後衛| x== 0 && y == 0,但我不確定這一點。

編輯:我使用-Wallghc轉載了警告,失蹤的警衛沒有擺脫這個警告。也許別人可以解釋一個。

+0

但即使我添加(沒有,沒有)&| x == 0 && y == 0,它仍然不工作T_T – libra

2

你的第一個錯誤是在第1行,246字,建議你在編譯之前失去了所有格式。

+0

Thx回答,但我應該如何解決它? – libra