用parsec解析递归数据 [英] Parse recursive data with parsec
本文介绍了用parsec解析递归数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import Data.Attoparsec.Text.Lazy
import Data.Text.Lazy.Internal(Text)
import Data.Text .Lazy(包)
数据List a = Nil |缺点a(列表a)
列表::文本
list = pack $ unlines
[0
,1
,2
,5
List Int
解析器可以实现从缺点0(缺点1(缺点2(缺点5缺陷)))
> list ?
ps :纯解析器不解析 [Int] code>并将其转换为
List Int
是更好的选择。
解决方案
像这样:
import Control.Applicative
- 有问题的其余进口
数据列表a =无|缺点(列表a)
导出显示 - 用于测试
- 有问题列表的定义
parseList :: Parser(List Int)
parseList = foldr缺点< $>许多(十进制< * endOfLine)
GHCi中的测试:
* Main> parse parseList list
DoneCons 0(Cons 1(Cons 2(Cons 5 Nil)))
import Data.Attoparsec.Text.Lazy
import Data.Text.Lazy.Internal (Text)
import Data.Text.Lazy (pack)
data List a = Nil | Cons a (List a)
list :: Text
list = pack $ unlines
[ "0"
, "1"
, "2"
, "5"
]
How can List Int
parser coud be implemented to parse Cons 0 (Cons 1 (Cons 2 (Cons 5 Nil)))
from list
?
ps: pure parser without parsing a [Int]
and converting it to List Int
is preferable.
解决方案
Like this:
import Control.Applicative
-- rest of imports as in question
data List a = Nil | Cons a (List a)
deriving Show -- for testing
-- definition of list as in question
parseList :: Parser (List Int)
parseList = foldr Cons Nil <$> many (decimal <* endOfLine)
Testing in GHCi:
*Main> parse parseList list
Done "" Cons 0 (Cons 1 (Cons 2 (Cons 5 Nil)))
这篇关于用parsec解析递归数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文