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 が書いた 2 番目のコードです。

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

実際、これらのスニペットの両方を ghci (バージョン 7.4.2) でコンパイルできました。注意すべきことは、スペースの代わりにタブを使用することです (SO に貼り付けてフォーマットすると失われる可能性があります)。

2 番目のスニペットに表示されるメッセージは、単なるコンパイラの警告です。の代わりに組み込みのパターン マッチングを使用して、コードを少しきれいにすることができますcase。同等の関数を次に示します。

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 に答える
1

あなたのコンパイラは私のものよりもうるさいですが、明らかに(Nothing,Nothing)ケースがありません。(Just _, Just _)あなたもガードを欠いているので、私が説明できるのはケースだけですが| x== 0 && y == 0、それについてはわかりません。

編集: -Wallonghcを使用して警告を再現しましたが、ガードが見つからないため、この警告が取り除かれません。他の誰かがそれを説明できるかもしれません。

于 2013-03-31T01:37:51.847 に答える