[Haskell-cafe] Syntax for modifying nested product types

Malcolm Wallace Malcolm.Wallace at cs.york.ac.uk
Fri Apr 23 11:11:40 EDT 2004

Mark Carroll <mark at chaos.x-philes.com> writes:

> For fairly flat things, the updates using field labels are okay. However,
> when I have a function that needs to tweak various bits of various "deep"
> fields, based on various conditions, then it gets really ugly, not least
> because of the conditions: foo { bar = baz } becomes,

>     let old = bar foo in foo { bar = if cond then f old else old }

> or whatever. Do I need such a let for each component and sub-component of
> the object that has a child that may be modified, or will

>     foo { bar = if cond then f (bar foo) else bar foo }

> be suitably optimised?

If the pattern is very common, how about just naming it?

    perhaps cond f field = if cond then f field else field

    foo { bar = perhaps cond0 f (bar foo)
        , wib = perhaps cond1 g (wib foo) }


More information about the Haskell-Cafe mailing list