IT練習ノート

IT関連で調べたこと(実際は嵌ったこと)を書いています。

PipesでHelloWorld

PipesでHelloWorld

Prelude Pipes P> runEffect $ (yield "Hello World" ) >-> P.stdoutLn
Hello World

Producerの型

Prelude Pipes P> :t (yield "Hello Wordl")
(yield "Hello Wordl") :: Monad m => Proxy x' x () [Char] m ()

Consumerの型

Prelude Pipes P> :t P.stdoutLn
P.stdoutLn :: MonadIO m => Proxy () String y' y m ()
Prelude Pipes P> 

合成の型

Prelude Pipes P> :t (>->)
(>->)
  :: Monad m =>
     Proxy a' a () b m r -> Proxy () b c' c m r -> Proxy a' a c' c m r
Prelude Pipes P> 

途中にMapを挟む

Prelude Pipes P> runEffect $ (yield "Hello World" ) >-> (P.map (\x -> "<" ++ x ++ ">" ) ) >-> P.stdoutLn
<Hello World>

yieldを続ける

Prelude Pipes P> runEffect $ (yield "Hello" ) >-> (yield "world") >-> P.stdoutLn
world

ProducerとConsumerを続ける

Prelude Pipes P> runEffect $ (yield "Hello" ) >-> P.stdoutLn >-> (yield "world") >-> P.stdoutLn
world

forでProducerをつなげる

Prelude Pipes P> runEffect $ (yield "Hello" ) `for` (\x -> yield (x ++ " world")) >-> P.stdoutLn
Hello world

Consumeしてしまうとそこで終わる。

Prelude Pipes P> runEffect $ (yield "Hello" ) >-> P.stdoutLn `for` (\x -> yield (x ++ " world")) >-> P.stdoutLn
Hello

標準入力と標準出力をつかった例(http://hackage.haskell.org/package/pipes-4.0.0/docs/Pipes-Tutorial.html

Prelude Pipes P> runEffect $ for stdinLn (lift . putStrLn)
aaa
aaa
bbb
bbb
cccc
cccc

出力をファイルに変更する(例外の取り扱いが良くないが)

Prelude Pipes P> runEffect $ for stdinLn (lift . (appendFile "./test03.txt") )
aaaaa
あ
fooo
bar
^CInterrupted.
Prelude Pipes P> 
$ cat test03.txt
aaaaaあfooobar$ 

ファイルからの入力に変更する(例外の取り扱いが良くないが)

Prelude Pipes P> :t lift (readFile "./test03.txt")
lift (readFile "./test03.txt") :: MonadTrans t => t IO String
Prelude Pipes P> runEffect $ for (lift (readFile "./test03.txt")) (lift . putStrLn)
"aaaaa\12354fooobar"