Haskell将一个字符串解析为数组数组

时间:2016-07-07 20:30:37

标签: arrays parsing haskell

我需要将一个String解析为数组数组。字符串在“数组”中按“\ n”字符分割。并且每个数组都被“,”或“;”分割。迹象。

示例:4;5\n6,7 -----> [[4,5][6,7]]

import qualified Text.Parsec as P (char,runP,noneOf,many,(<|>),eof)
import Text.ParserCombinators.Parsec
import Text.Parsec.String 
import Text.Parsec.Char
import Text.PrettyPrint.HughesPJ
import Data.Maybe

newtype CSV = CSV [Row] deriving (Show,Eq)
type Row = [String]

parseCSV :: Parser CSV
parseCSV = do
  return $ CSV (endBy (sepBy (many (noneOf ",\n")) (Text.Parsec.Char.char ',')) (Text.Parsec.Char.char '\n'))

runParsec :: Parser a -> String -> Maybe a
runParsec parser input = case P.runP parser () "" input of
    Left  _ -> Nothing
    Right a -> Just a

但是当我尝试运行代码时,由于数据类型错误而导致错误

1 个答案:

答案 0 :(得分:2)

这是一个将runParsec parseCSV "4;5\n6,7\n"解析为Just (CSV [["4","5"],["6","7"]])的解决方案。

parseCSV :: Parser CSV
parseCSV = CSV <$> csv
  where
    csv = row `endBy` char '\n'
    row = many (noneOf ",;\n") `sepBy` oneOf ",;"