我喜欢在Python解释器中即兴解析字符串。
>>> s = """Adams, John
... Washington,George
... Lincoln,Abraham
... Jefferson, Thomas
... """
>>> print "\n".join(x.split(",")[1].replace(" ", "")
for x in s.strip().split("\n"))
John
George
Abraham
Thomas
这在Python解释器中很好用,但我想使用Haskell/GHCi也实现类似的操作。问题是,我无法粘贴多行字符串。我可以使用带有EOF字符的getContents函数,但由于EOF字符会关闭stdin,所以我只能这样做一次。
Prelude> s <- getContents
Prelude> s
"Adams, John
Adams, John\nWashington,George
Washington,George\nLincoln,Abraham
Lincoln,Abraham\nJefferson, Thomas
Jefferson, Thomas\n^Z
"
Prelude> :{
Prelude| putStr $ unlines $ map ((filter (`notElem` ", "))
Prelude| . snd . (break (==','))) $ lines s
Prelude| :}
John
George
Abraham
Thomas
Prelude> x <- getContents
*** Exception: <stdin>: hGetContents: illegal operation (handle is closed)
有没有更好的方法在GHCi中完成这个步骤?注意-我对getContents(和Haskell IO总体)的理解可能严重失误。
更新
我会使用我收到的答案。这里有一些我做的辅助函数(剽窃),它们模拟了Python的"""引用(以"""
结尾,而不是开始)来自ephemient的答案。
getLinesWhile :: (String -> Bool) -> IO String
getLinesWhile p = liftM unlines $ takeWhileM p (repeat getLine)
getLines :: IO String
getLines = getLinesWhile (/="\"\"\"")
要在GHCi中使用AndrewC的答案 -
C:\...\code\haskell> ghci HereDoc.hs -XQuasiQuotes
ghci> :{
*HereDoc| let s = [heredoc|
*HereDoc| Adams, John
*HereDoc| Washington,George
*HereDoc| Lincoln,Abraham
*HereDoc| Jefferson, Thomas
*HereDoc| |]
*HereDoc| :}
ghci> putStrLn s
Adams, John
Washington,George
Lincoln,Abraham
Jefferson, Thomas
ghci> :{
*HereDoc| putStr $ unlines $ map ((filter (`notElem` ", "))
*HereDoc| . snd . (break (==','))) $ lines s
*HereDoc| :}
John
George
Abraham
Thomas