LoginSignup
2
1

More than 5 years have passed since last update.

特定の値を読み込むまでのConduit

Last updated at Posted at 2013-09-14

次のテキストファイルをENDが来る手前まで読み込みたい。

hogehoge.txt
waiwai
weiwei
yahoo
END
hoge
hoge

ConduitをtakeWhile :: (a -> Bool) -> [a] -> [a]みたいにして作りたい!

conduit_sample.hs
{-# LANGUAGE OverloadedStrings #-}
import Data.Conduit
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL

takeWhile' :: Monad m => (a -> Bool) -> Conduit a m a
takeWhile' f = do
  mx <- await
  case mx of
    Nothing -> return ()
    Just x
      | f x -> yield x >> takeWhile' f
      | otherwise -> return ()

main = do
  ss <-
    runResourceT $
    CB.sourceFile "hogehoge"
    $= CB.lines
    $= takeWhile' (/= "END")
    $$ CL.consume
  print ss

これでいい気がする。すごくMonadを普通に書くだけだった。

参考文献

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1