使用parsec解析递归数据

ДМИ*_*КОВ 4 haskell parsec recursive-datastructures attoparsec

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"
  ]
Run Code Online (Sandbox Code Playgroud)

如何List Int解析器coud实现解析Cons 0 (Cons 1 (Cons 2 (Cons 5 Nil)))list

ps:纯解析器而不解析a [Int]并将其转换List Int为更好.

kos*_*kus 6

像这样:

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)
Run Code Online (Sandbox Code Playgroud)

在GHCi中测试:

*Main> parse parseList list
Done "" Cons 0 (Cons 1 (Cons 2 (Cons 5 Nil)))
Run Code Online (Sandbox Code Playgroud)