模式匹配组合可能和Either

时间:2013-02-05 09:32:48

标签: haskell

如何匹配模式

Maybe (Either (Int, String) String)

我需要用这种输入编写函数以及如何解析这样的输入?

4 个答案:

答案 0 :(得分:7)

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

  • Nothing
  • Just (Left (x,y))其中xIntyString
  • Just (Right z)其中zString

答案 1 :(得分:3)

f :: Maybe (Either (Int, String) String) -> <SOMETHING>
f x = case x of
    Just (Left (i, s)) -> <...>
    Just (Right s) -> <...>
    Nothing -> <...>

答案 2 :(得分:2)

matchme Nothing = "Nothing"
matchme (Just (Left (x,y)) = "Left " ++ show x ++ " " + y
matchme (Just (Right z)) = "Right " ++ z

答案 3 :(得分:2)

还可以使用maybeeither函数,如下所示:

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