2012-11-24 226 views
-2

我试图写读类的实例来读取输入的字符串如下:阅读字符串输入

"1 3 -  
- 2 3  
- - 5" 

转换成[[Maybe Int]]

“ - ”将被翻译成Nothing “ 3" 将是Just 3

"('a',3) - ('b',7) 
('c',5) ('e',0) - 
('d',9) - ('h',8)" 

转换成[[Maybe (Char,Int)]]

“ - ”将被翻译成没什么 “(‘A’,3)”将Just ('a',3)

我试图用字符的处理列表给他们写,但它需要大量的工作。你有什么建议吗?对不起,我对Haskell很新,所以我问你这个问题。 :(

+0

其实,我想将其转换成[也许INT]]。 ' - '将被翻译为Nothing。 '3'将会是Char Char。但是一个字符串是相当一般的,它是未知的类型,只是知道参数是由一个空格或多个空格分隔的,而且它们被写入很多行(不是一行) – chipbk10

+0

这个编辑使得它更清晰,谢谢。 – AndrewC

+0

您可能对[这个问题]的答案感兴趣(http://stackoverflow.com/questions/13553794/read-instance-causes-parse-error/13554910#13554910) – AndrewC

回答

4

如果你摆脱了-条目,你可以很快做到这一点作为

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数据类型来表示对列表中的某些点没有值;我们可以使用-作为Nothinga的简写,作为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]] 
+0

我仍然必须处理' - ' ,并且字符串中的变量可以由一个或多个空格分隔。对不起,没有足够清楚 – chipbk10

+1

@ chipbk10我认为这个新的编辑可能会做你想做的。 – AndrewC

+0

哇,太好了。非常感谢@AndewC。我知道了。我正在寻找一些像Pandoc或Text.Parsec这样的模块。但是,我们可以在不使用解析器的外部模块的情况下解析它,这真是一个惊喜。 – chipbk10