[Haskell-cafe] sections for record settors

Tim Newsham newsham at lava.net
Tue Sep 19 17:28:47 EDT 2006


Hi,
    When you create a record in haskell, it automatically generates
gettor functions for accessing the record fields.  It also provides
you with a record update syntax:

     rec {field=val}

but there is no settor function.  It would be nice if there was some
sort of section-like syntax to access the settor function, like:

     {field=} -- val rec
     {field=val} -- rec

or even if there was a name for that function (such as field_settor).
Without such a syntax, one often has to write lambdas like:

     \r v -> r {field=v}
     \r -> r {field=3}

Consider for example an cmd line parser that collects flags in
a record.  Instead of writing:

     opt "l" (NoArg  {c_loop=False})        "dont loop",
     opt "o" (optStr {c_out=} "dir")        "output dir",
     opt "t" (optInt {c_maxtime=} "mins")   "maximum time"

we would have to write it out as:

options = [
     opt "l" (NoArg  (\c   -> c {c_loop=False}))         "dont loop",
     opt "o" (optStr (\v c -> c {c_out=v}) "dir")        "output dir",
     opt "t" (optInt (\v c -> c {c_maxtime=v}) "mins")   "maximum time"
     ] where
         opt cs d s = Option cs [] d s
         optStr f name = ReqArg f name
         optInt f name = ReqArg (f . read) name

getOptions :: String -> [String] -> IO Config
getOptions prog argv =
     let header = "Usage:  " ++ prog ++ " [OPTIONS...] files..." in
     let usage s = ioError (userError (s ++ "\n" ++ usageInfo header 
options)) in
     let (updates, files, errs) = getOpt2 options argv in
     let config = updates defConfig {c_files=files} in
     case () of
       _ | not (null errs)           -> usage (concat errs)
         | null (c_files config)     -> usage "no files specified"
         | otherwise                 -> return config


Tim Newsham
http://www.thenewsh.com/~newsham/


More information about the Haskell-Cafe mailing list