3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Haskell小話①] >>=の代わりに=<<で可読性をチョイあげ

Last updated at Posted at 2014-12-26

あいさつ

Haskellや圏論ではおなじみのバインド

(>>=)  :: m a -> (a -> m b) -> m b

の逆バージョンの=<< を使うと可読性があがる場面は多い.

(=<<)  :: (a -> m b) -> m a -> m b

=<< を使ってリファクタリング!

まずこんなコードを例に取ります.

main = do
  args <- getArgs
  mapM_ putStrLn args

端末から引数を受け取ってIOモナドから値を取り出してputStrLnで出力する簡単な例です.

(出力もIOモナドで包まないといけないのでmapM_ を使う事に注意されたい)

このコードをdoを使わずに書こうと思ったら、

main = getArgs >>= mapM_ putStrLn

というのがパッと浮かぶと思うのですが、
(Haskell力が低いからかもしれません)

ここは一つ

main = mapM_ putStrLn =<< getArgs

と書いてみると、おおよそ

main = map putStrLn getArgs

みたいにとらえる事が出来て可読性があがるよね!foo↑

つまり関数を左辺に、モナドに包まれたものを右辺におくと通常の関数ぽくみなせてすごく良い.

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?