Generating "setMember" functions for record structures

Peter Simons simons at cryp.to
Tue Sep 23 16:06:19 EDT 2003


Hi,

in one of my programs, I have to modify individual fields of a pretty
large record structure quite frequently. Assume the structure is:

> data State     = State { foo :: [Int]
>                        , bar :: [String]
>                        }

Then I'd like to have functions setFoo and setBar, which copy a State
but replace the field in question with a given value. This is
implemented as:

> setFoo        :: State -> [Int] -> State
> setFoo st x    = State { foo = x
>                        , bar = bar st
>                        }

> setBar        :: State -> [String] -> State
> setBar st x    = State { foo = foo st
>                        , bar = x
>                        }

Now, defining these helper functions for large records is not what I
call an interesting job.

Thus I wonder, is there any way to automate this task? I thought about
using Template Haskell, but I haven't used it at all yet and am
uncertain about how difficult accomplishing this would be.

I also thought about using "Data.Generics", which I know better, but
the generic approach feels like over-kill for this task. In order to
use it, I'd have to re-design my data structure as well. So this isn't
too attractive ...

Any ideas? Comments? Source Code? :-)

Peter



More information about the Haskell-Cafe mailing list