[Haskell-cafe] How to write elegant Haskell programms? (long posting)

David Roundy droundy at darcs.net
Mon Jan 29 15:48:25 EST 2007

On Mon, Jan 29, 2007 at 08:14:55PM +0100, Michael Roth wrote:
> Hello list,


Just to simplify one function...

> logdir      = "/var/log"
> makeOldname :: String -> String
> makeOldname fn = logdir ++ '/' : fn
> main :: IO ()
> main = do
>   files <- liftM (filter isLogfile) (getDirectoryContents logdir)
>   let oldnames = map makeOldname files
>   times <- mapM getModificationTime oldnames

main = do files <- liftM (filter isLogfile) (getDirectoryContents logdir)
          times <- mapM (getModificationTime . ("/var/log/"++)) files

(also consider)

main = do files <- filter isLogfile `fmap` getDirectoryContents logdir
          times <- (getModificationTime . ("/var/log/"++)) `mapM` files

If you count reindenting of the first line of the do statement and removal
of type signatures, I've eliminated six out of eight lines, and the
resulting function doesn't need to be read like spaghetti, looking back and
forth to find out what makeOldname and logdir are.  Of course, if you
expect to change logdir or use it elsewhere in the code, you still might
want to give it a name.  But my versions I'd say are more readable and much
more compact.

On large projects it's worthwhile using type declarations for top-level
functions, and it's worth adding them while debugging (to get better error
messages), or for tricky functions where the types aren't obvious.  But for
code like this, they just make it harder to read.
David Roundy
Department of Physics
Oregon State University
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070129/2dfbc887/attachment.bin

More information about the Haskell-Cafe mailing list