2

Coming from an OOP background, I've got some issues with the concept of immutable objects/records/messages in functional programming.

Lets say I pass an PurchaseOrder record through a pipeline of functions where each function is supposed to add or update data in this record.

When dealing with mutable state, I would simply set some specific properties of the message beeing passed around.

When dealing immutable records, are there some design tricks making things easier on this matter? Copying every single field in order to change just one field is just a pain.

{ A = x.A ; B = x.B ; C = x.C ; D = x.D ; E = somethingnew; }

I guess grouping data as much as possible is a good way to deal with it, thus avoiding to copy all fields. Are there any other ways or design guidelines for this?

4

2 回答 2

9

你可以做

 let myRecord3 = { myRecord2 with Y = 100; Z = 2 }

(来自 MSDN 记录页面的示例 - http://msdn.microsoft.com/en-us/library/dd233184.aspx

于 2012-07-09T09:38:51.513 回答
0

我来自一个非常纯粹和极端主义的 OOP 背景,我的 OOP 设计往往是 99% 的不可变对象(即使是允许变异的语言)。如果您有一个函数管道,其中每个函数都应该添加或更新记录中的数据,根据我的经验,每个函数都将处理该记录的子问题和子概念,因此您应该为每个函数创建一个类/类型/任何内容其中遵循 OOP 最佳实践,如SRPSoC. 如果任何类/记录/类型有超过 4 或 5 个字段/变量/属性,我认为您可能在那里承担了太多责任。如果将问题拆分为多个子问题,则管道的每个函数都会创建记录的子记录,而主函数会将它们全部组合起来以创建主记录。根据我遵循传统 OOP 的经验,您可以进行一种设计,使您能够在没有任何变化的情况下实现您想要实现的目标。

于 2012-07-10T02:54:11.240 回答