简体   繁体   English

Haskell模式匹配中的错误

[英]An error in Haskell pattern matching

This is one of my lab question, I have to write a maybeDiv function, and here is my work. 这是我的实验问题之一,我必须编写一个maybeDiv函数,这是我的工作。 There is an error in Just xy , May I ask what causes this error? Just xy存在错误,请问是什么原因导致此错误? Thanks. 谢谢。

maybeDiv :: Maybe Integer -> Maybe Integer -> Maybe Integer
maybeDiv mx my = case mx my of
    Just x y
      | y == 0 -> Just Nothing
      | otherwise -> Just (x / y)
    Nothing -> Nothing

Your program should rather looks like: 您的程序应该看起来像这样:

maybeDiv :: Maybe Integer -> Maybe Integer -> Maybe Integer
maybeDiv mx my = case (mx, my) of
    (Just x, Just y)
      | y == 0 -> Nothing
      | otherwise -> Just (x / y)
    _ -> Nothing

My PC is currently busy with doing a huge animation so I cannot check. 我的PC当前正在忙于制作大型动画,因此无法检查。 I'll check later unless someone corrects me before. 除非有人纠正我,否则我以后再检查。

But that will not work because x/y is not an Integer. 但这将不起作用,因为x/y不是整数。 You should rather want a Double . 您宁愿要Double So: 所以:

maybeDiv :: Maybe Integer -> Maybe Integer -> Maybe Double
maybeDiv mx my = case (mx, my) of
    (Just x, Just y)
      | y == 0 -> Nothing
      | otherwise -> Just (fromInteger x / fromInteger y)
    _ -> Nothing

Edit 编辑

If you are not allowed to use the 2-tuple (mx,my) , as you said in a comment, you can do: 如果不允许您使用2元组(mx,my) ,如您在评论中所述,则可以执行以下操作:

maybeDiv :: Maybe Integer -> Maybe Integer -> Maybe Double
maybeDiv mx my =
  case my of
    Nothing -> Nothing
    Just 0  -> Nothing
    Just y  -> case mx of
      Nothing -> Nothing
      Just x  -> Just (fromInteger x / fromInteger y)

If you want the quotient of the Euclidean division as the output, do: 如果要将欧几里得除数的商作为输出,请执行以下操作:

maybeDiv :: Maybe Integer -> Maybe Integer -> Maybe Integer
maybeDiv mx my =
  case my of
    Nothing -> Nothing
    Just 0  -> Nothing
    Just y  -> case mx of
      Nothing -> Nothing
      Just x  -> Just (x `quot` y)

You could also generalize the function in order that it accepts Integer and Int types, like this: 您也可以泛化该函数以使其接受IntegerInt类型,如下所示:

maybeDiv :: Integral a => Maybe a -> Maybe a -> Maybe a
maybeDiv mx my =
  case my of
    Nothing -> Nothing
    Just 0  -> Nothing
    Just y  -> case mx of
      Nothing -> Nothing
      Just x  -> Just (x `quot` y)

Since this is for a lab, you might not be allowed to use Applicative - however, for the sake of clarity, here's what your function could/should actually be: 由于这是在实验室中进行的,因此您可能不被允许使用Applicative-但是,为清楚起见,以下是您的功能可能/应该是的:

maybeDiv :: Maybe Int -> Maybe Int -> Maybe Int
maybeDiv ma mb = quot <$> ma <*> mb

This will end up equivalent to the other answers, but might be a lot cleaner to read. 这最终将等同于其他答案,但是可能更容易阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM