Pointfree/Combine

From HaskellWiki
< Pointfree
Revision as of 05:21, 29 November 2006 by DonStewart (talk | contribs) (a page for `combine')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

A program to number lines of a file, just for fun, using the 'combine' function found with @pl in #haskell.

import Control.Monad
import Text.Printf
import System.Environment

combine :: (Monad m) => m a -> (a -> b -> c) -> m b -> m c
combine a f b = (b >>=) . (return .) . f =<< a

main = do [f] <- getArgs
          ls  <- combine (return [(1::Int)..])
                         (zipWith (printf "%4d %s"))
                         (lines `fmap` readFile f)
          mapM_ putStrLn ls

When run:

$ runhaskell A.hs A.hs
   1 import Control.Monad
   2 import Text.Printf
   3 import System.Environment
   4
   5 combine :: (Monad m) => m a -> (a -> b -> c) -> m b -> m c
   6 combine a f b = (b >>=) . (return .) . f =<< a
   7
   8 main = do [f] <- getArgs
   9           ls  <- combine (return [(1::Int)..])
  10                          (zipWith (printf "%4d %s"))
  11                          (lines `fmap` readFile f)
  12           mapM_ putStrLn ls