-2

如何匹配模式

Maybe (Either (Int, String) String)

我需要用这种输入编写函数,如何解析这种输入?

4

4 回答 4

7

Maybe a类型有模式Just aNothingEither a b类型有模式Left aRight b。因此类型的值Maybe (Either (Int, String) String)可以匹配以下模式:

  • Nothing
  • Just (Left (x,y))哪里x是一个Int并且y是一个String
  • Just (Right z)哪里zString
于 2013-02-05T09:36:20.890 回答
3
f :: Maybe (Either (Int, String) String) -> <SOMETHING>
f x = case x of
    Just (Left (i, s)) -> <...>
    Just (Right s) -> <...>
    Nothing -> <...>
于 2013-02-05T09:36:26.837 回答
2
matchme Nothing = "Nothing"
matchme (Just (Left (x,y)) = "Left " ++ show x ++ " " + y
matchme (Just (Right z)) = "Right " ++ z
于 2013-02-05T09:38:12.167 回答
2

也可以使用maybeandeither函数,如下所示:

matchit = maybe nothing (left `either` right)
  where
      nothing = {- value for the nothing case -}
      left (x,y) = {- code for the (Just (Left (x,y)) case -}
      right z = {- code for the (Just (Right z)) case -}
于 2013-02-05T10:33:29.073 回答