如果你摆脱了这些-
条目,你可以很快地做到这一点
Prelude> (map (map read) . map words. lines $ "('a',3) ('b',4)\n('c',5)")::[[(Char,Int)]]
[[('a',3),('b',4)],[('c',5)]]
或者将其定义为一个函数
genericReadLines :: Read a => String -> [[a]]
genericReadLines = map (map read) . map words. lines
您可以这样使用:
*Main> (genericReadLines "('a',3) ('b',4)\n('c',5)")::[[(Char,Int)]]
[[('a',3),('b',4)],[('c',5)]]
但你可能会发现这样做更容易
readCharInts :: String -> [[(Char,Int)]]
readCharInts = genericReadLines
readInts :: String -> [[Int]]
readInts = genericReadLines
所以你可以输入
*Main> readInts "1 2 3\n4 5 6\n7 8 9"
[[1,2,3],[4,5,6],[7,8,9]]
*Main> readCharInts "('a',3) ('b',4)\n('c',5)"
[[('a',3),('b',4)],[('c',5)]]
但是保留-
? 您必须使用 Maybe 数据类型来表示列表中某些点没有值;我们可以-
用作 的简写Nothing
和a
的简写Just a
。
read' :: Read a => String -> Maybe a
read' "-" = Nothing
read' xs = Just (read xs)
我应该警告您,如果您的数据可能是,那么该代码是脆弱的'-'
,但也许不能。
genericMaybeReadLines :: Read a => String -> [[Maybe a]]
genericMaybeReadLines = map (map read') . map words. lines
然后我们可以有
readMaybeCharInts :: String -> [[Maybe (Char,Int)]]
readMaybeCharInts = genericMaybeReadLines
readMaybeInts :: String -> [[Maybe Int]]
readMaybeInts = genericMaybeReadLines
所以现在我们可以做
*Main> readMaybeCharInts "('a',3) ('b',4)\n- ('c',5)"
[[Just ('a',3),Just ('b',4)],[Nothing,Just ('c',5)]]
*Main> readMaybeInts "2 3 -\n4 - 2"
[[Just 2,Just 3,Nothing],[Just 4,Nothing,Just 2]]