如何匹配模式
Maybe (Either (Int, String) String)
我需要用这种输入编写函数,如何解析这种输入?
Maybe a
类型有模式Just a
和Nothing
。Either a b
类型有模式Left a
和Right b
。因此类型的值Maybe (Either (Int, String) String)
可以匹配以下模式:
Nothing
Just (Left (x,y))
哪里x
是一个Int
并且y
是一个String
Just (Right z)
哪里z
是String
。f :: Maybe (Either (Int, String) String) -> <SOMETHING>
f x = case x of
Just (Left (i, s)) -> <...>
Just (Right s) -> <...>
Nothing -> <...>
matchme Nothing = "Nothing"
matchme (Just (Left (x,y)) = "Left " ++ show x ++ " " + y
matchme (Just (Right z)) = "Right " ++ z
也可以使用maybe
andeither
函数,如下所示:
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 -}