newtype Parser a = PsrOf{
-- | Function from input string to:
--
-- * Nothing, if failure (syntax error);
-- * Just (unconsumed input, answer), if success.
dePsr :: String -> Maybe (String, a)}
我想创建一种新型的Parser来查看它的外观。
我尝试了
*ParserLib> PsrOf{"hello"}
但是出现错误
<interactive>:5:7: error: parse error on input ‘"’
答案 0 :(得分:3)
您已经创建了类型。现在,您要创建该类型的 value 。为此,您需要使用类型为PsrOf
的值来调用String -> Maybe (String, a)
。例如:
newtype Parser a = PsrOf { dePsr :: String -> Maybe (String, a) }
get3 :: String -> Maybe (String, Int)
get3 ('3':xs) = Just (xs, 3)
get3 _ = Nothing -- Any string, including the empty string, that doesn't start with '3'
get3P :: Parser Int
get3P = PsrOf get3
要实际使用解析器,您需要先提取函数,然后再将其应用于字符串:
dePsr get3P "38" -- Just ("8", 3)
dePsr get3P "" -- Nothing
dePsr get3P "hello" -- Nothing
这里的记录语法仅用于简化类型的定义,而不是编写
newtype Parser a = PsrOf (String -> Maybe (String, a))
dePsr :: Parser a -> String -> Maybe (String, a)
dPsr (PsrOf f) = f
记录语法的其余用途(模式匹配或对值进行稍微修改的副本)实际上不适用于包装单个值的类型。