Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
850 views
in Technique[技术] by (71.8m points)

haskell - Shorthand way for assigning a single field in a record, while copying the rest of the fields?

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) }

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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" }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...