我正在尝试在case子句中执行模式匹配:
-- different types of Parsers:
-- type Parser = String -> Maybe (String, String)
-- type Parser = String -> Maybe (Tree, String)
-- type Parser = String -> Maybe (Int, String)
-- can be generalized as:
data Parser a = Parser (String -> Maybe (a, String))
class Monad' m where
result :: a -> m a
bind :: m a -> (a -> m b) -> m b
instance Monad' Parser where
result v = Parser (\input -> Just (v, input))
bind (Parser fa) fb = Parser (\input ->
case (fa input) of
Nothing -> Nothing
Just(v, input') -> pb input' where pb in fb v = (Parser pb)
)
问题出在where pb in fb v = (Parser pb)
上。如何声明pb,然后与对(fb input')的调用进行模式匹配。
另外,在声明:Parser
中包含构造函数data Parser a = Parser (String -> Maybe (a, String))
的需求似乎使事情变得非常复杂。这样写起来会简单得多:
data Parser a = String -> Maybe (a, String)
,但这是不可能的,还有其他方法可以实现吗?
答案 0 :(得分:3)
您可以使用let
或where
在允许这些表达式的任何位置创建模式匹配:(缩短一些行使其适合StackOverflow的格式)
instance Monad' Parser where
result v = Parser (\input -> Just (v, input))
bind (Parser fa) fb =
Parser (\input -> case (fa input) of
Nothing -> Nothing
Just(v, input') -> pb input'
where (Parser pb) = fb v
)
=或=
instance Monad' Parser where
result v = Parser (\input -> Just (v, input))
bind (Parser fa) fb =
Parser (\input -> case (fa input) of
Nothing -> Nothing
Just(v, input') ->
let (Parser pb) = fb v
in pb input'
)
Haskell 98不允许类型同义词的实例声明。 GHC刊登广告宣传一种允许这样做的语言扩展,但是我的经验是,它导致了越来越多的问题。
解决模式匹配需求的标准方法是创建一条记录,并使用该字段剥离构造函数。惯例似乎是使用un
++的类型名称。
data Parser a = Parser { unParser :: (String -> Maybe (a, String))}
-- N.B. unParser :: Parser a -> String -> Maybe (a, String)
instance Monad' Parser where
result v = Parser (\input -> Just (v, input))
bind (Parser fa) fb =
Parser (\input -> case (fa input) of
Nothing -> Nothing
Just(v, input') -> unParser (fb v) input
)
您没有问的问题
您知道Maybe
是Monad
吗?当您发现自己编写了大量额外的代码来传播Nothing -> Nothing
时,不理会失败并让Monad(或Applicative)实例成为您的朋友真是太好了。
instance Monad' Parser where
result v = Parser (\input -> Just (v, input))
bind (Parser fa) fb =
Parser (\input -> do -- This is in the Maybe Monad.
-- If any step fails the result is Nothing
(v, input') <- fa input
unParser (fb v) input'
)