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) に関する私の理解は、おそらく深刻に壊れています。

更新しました

私は受け取った答えで遊んでいます。ここに私が作成した(盗作した)いくつかのヘルパー関数があります。これは、ephemientの回答からのPythonの"""引用(開始ではなく、で終わることによって)をシミュレートします。"""

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
4

2 に答える 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)
アダムス、ジョン
ワシントン、ジョージ
リンカーン、エイブラハム
トーマス・ジェファーソン

「アダムス、ジョン\nワシントン、ジョージ\nリンカーン、エイブラハム\nジェファーソン、トーマス\n」
ghci>
于 2012-08-25T06:33:00.513 に答える
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

<<"EOF"これは、複数行の文字列リテラルをコード (perlや pythonなど) に貼り付けることができるヘルパー モジュール、HereDoc を使用します"""。これを行う方法をどのように見つけたか思い出せませんが、最初と最後の行の空白を削除するように微調整したので、改行でデータを開始および終了できます。

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

于 2012-08-25T17:44:53.067 に答える