haskell 正在解析上下文无关语法以与字符串进行比较
haskell parsing contextfree-grammar to compare with a string
我试图表示一个上下文无关的语法,我想解析它以将字符串与 Prod "A" [NT "B", NT "C"]
的 "A"
进行比较,但我不知道如何,有人可以请帮帮我?
data Symbol a b = T a | NT b
deriving (Eq,Show)
data Produktion a b = Prod b [Symbol a b]
deriving (Eq,Show)
type Produktionen a b = [Produktion a b]
liste11 = [Prod "A" [NT "B", NT "C"]
,Prod "B" [NT "D", NT "E"]
,Prod "D" [T "d"]
] --
有更简单的方法,但可以使用原始方法
fromNT :: (Symbol a b) -> b
fromNT (NT b) = b
fromNT (T a) = undefined
extractNT :: (Eq b) => b -> [Produktion a b] -> [[b]]
extractNT _ [] = [[]]
extractNT b (p:ps) | is p = (map fromNT (symbol p)) : extractNT b ps
| otherwise = []
where is (Prod x xs) = x==b
symbol (Prod _ xs) = xs
现在你可以写了
> extractNT "A" liste11
[["B","C"]]
更新
我认为它不适用于泛型类型,但适用于 String String
value :: (Symbol String String) -> String
value (T a) = a
value (NT b) = b
其他访问器仍然可以是通用的
symbol :: (Produktion a b) -> [Symbol a b]
symbol (Prod _ ss) = ss
tag :: (Produktion a b) -> b
tag (Prod b _) = b
你现在可以说
> map (map value) $ map symbol $ filter (\p -> tag p=="D") liste11
[["d"]]
> map (map value) $ map symbol $ filter (\p -> tag p=="A") liste11
[["B","C"]]
我试图表示一个上下文无关的语法,我想解析它以将字符串与 Prod "A" [NT "B", NT "C"]
的 "A"
进行比较,但我不知道如何,有人可以请帮帮我?
data Symbol a b = T a | NT b
deriving (Eq,Show)
data Produktion a b = Prod b [Symbol a b]
deriving (Eq,Show)
type Produktionen a b = [Produktion a b]
liste11 = [Prod "A" [NT "B", NT "C"]
,Prod "B" [NT "D", NT "E"]
,Prod "D" [T "d"]
] --
有更简单的方法,但可以使用原始方法
fromNT :: (Symbol a b) -> b
fromNT (NT b) = b
fromNT (T a) = undefined
extractNT :: (Eq b) => b -> [Produktion a b] -> [[b]]
extractNT _ [] = [[]]
extractNT b (p:ps) | is p = (map fromNT (symbol p)) : extractNT b ps
| otherwise = []
where is (Prod x xs) = x==b
symbol (Prod _ xs) = xs
现在你可以写了
> extractNT "A" liste11
[["B","C"]]
更新
我认为它不适用于泛型类型,但适用于 String String
value :: (Symbol String String) -> String
value (T a) = a
value (NT b) = b
其他访问器仍然可以是通用的
symbol :: (Produktion a b) -> [Symbol a b]
symbol (Prod _ ss) = ss
tag :: (Produktion a b) -> b
tag (Prod b _) = b
你现在可以说
> map (map value) $ map symbol $ filter (\p -> tag p=="D") liste11
[["d"]]
> map (map value) $ map symbol $ filter (\p -> tag p=="A") liste11
[["B","C"]]