分配记录中的单个字段,同时复制其余字段的速记方法? [英] Shorthand way for assigning a single field in a record, while copying the rest of the fields?
本文介绍了分配记录中的单个字段,同时复制其余字段的速记方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下记录 ADT:
Let's say I have the following record ADT:
data Foo = Bar { a :: Integer, b :: String, c :: String }
我想要一个函数,它接受一条记录并返回一条记录(相同类型),其中除了一个字段之外的所有字段都具有与作为参数传递的字段相同的值,如下所示:
I want a function that takes a record and returns a record (of the same type) where all but one of the fields have identical values to the one passed as argument, like so:
walkDuck x = Bar { a = a x, b = b x, c = lemonadeStand (a x) (b x) }
上述方法有效,但对于包含更多字段的记录(例如 10
),创建这样的函数将需要大量输入,我认为这是非常不必要的.
The above works, but for a record with more fields (say 10
), creating a such function would entail a lot of typing that I feel is quite unnecessary.
有没有什么不那么乏味的方法来做同样的事情?
Are there any less tedious ways of doing the same?
推荐答案
是的,有一种更新记录字段的好方法.在 GHCi 中你可以做 --
Yes, there's a nice way of updating record fields. In GHCi you can do --
> data Foo = Foo { a :: Int, b :: Int, c :: String } -- define a Foo
> let foo = Foo { a = 1, b = 2, c = "Hello" } -- create a Foo
> let updateFoo x = x { c = "Goodbye" } -- function to update Foos
> updateFoo foo -- update the Foo
Foo {a = 1, b = 2, c = "Goodbye" }
这篇关于分配记录中的单个字段,同时复制其余字段的速记方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文