Haskell GHCi - 如何使用EOF字符与getContents一起读取标准输入?

6
我喜欢在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
2个回答

6

getContents 等同于 hGetContents stdin. 不幸的是, hGetContents 会将其句柄标记为(半)关闭状态,这意味着任何试图再次从 stdin 读取的东西都会失败。

只读到一个空行或其他标记就足够了吗?不需要关闭 stdin 吗?

takeWhileM :: Monad m => (a -> Bool) -> [m a] -> m [a]
takeWhileM p (ma : mas) = do
    a <- ma
    if p a
      then liftM (a :) $ takeWhileM p mas
      else return []
takeWhileM _ _ = return []
ghci> liftM unlines $ takeWhileM (not . null) (repeat getLine)
"Adams, John\nWashington, George\nLincoln, Abraham\nJefferson, Thomas\n"
ghci>
这是一个在ghci中运行的表达式,它会重复获取用户输入的非空字符串,并将它们作为字符串列表返回,直到用户输入了一个空字符串。然后,使用liftM和unlines函数将列表转换为单个字符串,其中字符串之间用换行符分隔。

谢谢!我想知道如何在Windows上手动打开stdin句柄。无论哪种方式,现在都可以工作。我根据您的答案制作了一些辅助函数(已更新在我的问题中)。 - pyrospade

2
如果您经常这样做,并且正在某个模块中编写辅助函数,为什么不彻底使用您的编辑器处理原始数据呢?
{-# LANGUAGE TemplateHaskell, QuasiQuotes #-}
module ParseAdHoc where
import HereDoc
import Data.Char (isSpace)
import Data.List (intercalate,intersperse)  -- other handy helpers

-- ------------------------------------------------------
-- edit this bit every time you do your ad-hoc parsing

adhoc :: String -> String
adhoc = head . splitOn ',' . rmspace

input = [heredoc|
Adams, John
Washington,George
Lincoln,Abraham
Jefferson, Thomas
|]

-- ------------------------------------------------------
-- add other helpers you'll reuse here

main = mapM_ putStrLn.map adhoc.lines $ input

rmspace = filter (not.isSpace)

splitWith :: (a -> Bool) -> [a] -> [[a]]   -- splits using a function that tells you when
splitWith isSplitter list =  case dropWhile isSplitter list of
  [] -> []
  thisbit -> firstchunk : splitWith isSplitter therest
    where (firstchunk, therest) = break isSplitter thisbit

splitOn :: Eq a => a -> [a] -> [[a]]       -- splits on the given item
splitOn c = splitWith (== c)

splitsOn :: Eq a => [a] -> [a] -> [[a]]    -- splits on any of the given items
splitsOn chars = splitWith (`elem` chars)

使用takeWhile (/=',')head . splitOn ','更容易,但我认为在未来splitOn会更有用。

这里使用了一个辅助模块HereDoc,它允许您将多行字符串文字粘贴到代码中(就像perl的<<"EOF"或python的""")。我记不清我是如何发现这个方法的,但我已经对其进行了微调,以删除第一行和最后一行的空格,以便我可以用换行符开始和结束我的数据。

module HereDoc where
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Data.Char (isSpace)

{-
example1 = [heredoc|Hi.
This is a multi-line string.
It should appear as an ordinary string literal.

Remember you can only use a QuasiQuoter
in a different module, so import this HereDoc module 
into something else and don't forget the
{-# LANGUAGE TemplateHaskell, QuasiQuotes #-}|]

example2 = [heredoc|         
This heredoc has no newline characters in it because empty or whitespace-only first and last lines are ignored
                   |]
-}


heredoc = QuasiQuoter {quoteExp = stringE.topAndTail,
                       quotePat = litP . stringL,
                       quoteType = undefined,
                       quoteDec = undefined}

topAndTail = myunlines.tidyend.tidyfront.lines

tidyfront :: [String] -> [String]
tidyfront [] = []
tidyfront (xs:xss) | all isSpace xs = xss
                   | otherwise      = xs:xss

tidyend :: [String] -> [String]
tidyend [] = []
tidyend [xs]     | all isSpace xs = []
                 | otherwise = [xs]
tidyend (xs:xss) = xs:tidyend xss

myunlines :: [String] -> String
myunlines [] = ""
myunlines (l:ls) = l ++ concatMap ('\n':) ls

你可能会发现Data.Text是一个好的(灵感来源)辅助函数的来源: http://hackage.haskell.org/packages/archive/text/latest/doc/html/Data-Text.html

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接