如何编写更新记录字段的通用函数(How to write a generic function that updates fields of a Record)

[db:摘要]

如何编写更新记录字段的通用函数(How to write a generic function that updates fields of a Record)

考虑

type alias Rec = { a: Int, b: Int, c:Int } updateRec r aVal = { r|a = aVal } updateRec2 r aVal bVal = { r|a = aVal, b= bVal } updateRec3 r aVal bVal cVal = ...

如何将updateRec和updateRec2 ...概括为一个函数?

Consider

type alias Rec = { a: Int, b: Int, c:Int } updateRec r aVal = { r|a = aVal } updateRec2 r aVal bVal = { r|a = aVal, b= bVal } updateRec3 r aVal bVal cVal = ...

How to generalize updateRec and updateRec2... into one function?

最满意答案

这是做同样事情的更好方法:

updateA : Int -> Rec -> Rec updateA x rec = { rec | a = x } -- Similarly for b, c

现在您可以执行以下操作,假设您已经有值rec : Rec想要更新:

myUpdatedRec : Rec myUpdatedRec = rec |> updateA 7 |> updateB 19

您现在可以通过串联更新任意数量的字段|> updateX ...

Here's a better way of doing the same thing:

updateA : Int -> Rec -> Rec updateA x rec = { rec | a = x } -- Similarly for b, c

Now you can do the following, supposing you already have a value rec : Rec you want to update:

myUpdatedRec : Rec myUpdatedRec = rec |> updateA 7 |> updateB 19

You can now update an arbitrary number of fields by stringing together |> updateX ....

发布者:admin,转转请注明出处:http://www.yc00.com/web/1692676626a628266.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信