如何匹配模式
Maybe (Either (Int, String) String)
我需要用这种输入编写函数以及如何解析这样的输入?
答案 0 :(得分:7)
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
。答案 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)
还可以使用maybe
和either
函数,如下所示:
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 -}