[Haskell-cafe] record update
Henning Thielemann
lemming at henning-thielemann.de
Sat Sep 11 15:42:18 EDT 2010
On Sat, 11 Sep 2010, Jonathan Geddes wrote:
> On Sat, Sep 11, 2010 at 11:53 AM, Henning Thielemann
>>
>> data-accessor and similar packages may become your friends.
>>
>> data-accessor allows you to write:
>>
>> someUpdate =
>> (field1 ^: f) .
>> (field2 ^: g) .
>> (field3 ^: h)
>>
>
> data-accessor is a pretty cool package, but if I understand correctly,
> your "fields" are not the same as the straight functions you get from
> defining a record,
right
> and cant' be used as regular functions.
right
> So you have to create these Data.Accessor.Accessors.
right
> Is defining accessors really any better than just writing update
> functions like the following?
It's just, that you can use the same name for all kinds of access (set,
get, modify) and have nice combinators.
>> updateField1 :: (Field1Type -> Field1Type) -> MyRecord -> MyRecord
>> updateField1 f x = x{field1 = f $ field1 x}
>> someUpdate = (updateField1 f) . j(updateField2 g) . (updateField3 h)
>
> I understand that there is a package data-accessor-template for
> generating accessors, but couldn't you use TH for generating updater
> functions as well?
Sure. But what about names? You would need distinct names for 'get' (like
'field1') and 'modify' (like 'updateField1'), but then you can also write
update field1 (or (modify field1) as in data-accessor)
> It seems like something as fundamental as record update should have a
> clean, build-in syntax. Or am I thinking too imperatively?
I think accessors are even more functional than the built-in record
syntax. You can nicely combine them with Category's '.' operator in order
to access fields in sub-records. It would be cool, if the field
identifiers of Haskell records would be Accessors and not just Getters.
This would be a recursive problem, since Accessor is itself a record.
However, field names could represent functions of type
record -> (field, field -> record) .
More information about the Haskell-Cafe
mailing list