[英]Updating a single field in a record with Haskell @
I need to update one field of a very large default record. 我需要更新非常大的默认记录的一个字段。
As the default may change I don't want to rebuild the entire record manually. 由于默认值可能会更改,因此我不想手动重建整个记录。
Now I have come across the following way of doing this, but I am not sure how it works: 现在,我遇到了以下方法,但是我不确定它是如何工作的:
unaggregate :: MyResult -> MyResult
unaggregate calc@MyResult{..} = calc{ the_defaults = the_override
`mappend` the_defaults }
where
the_override = create ("aggregation" := False)
I have tried searching for 'Haskell @ operator' in Google but it does not return immediately useful information. 我尝试在Google中搜索“ Haskell @运算符”,但是它不会立即返回有用的信息。
I saw somewhere calc@MyResult{..}
does pattern matching on variables but I don't see what variable calc
does for the MyResult
record... 我在某个地方看到calc@MyResult{..}
对变量进行模式匹配,但是我看不到calc
对MyResult
记录有什么作用...
Also I have looked up mappend
(and Monoids) and I am not sure how these work either... 我也mappend
了mappend
(和mappend
),我也不知道它们是如何工作的...
Thank you for any help 感谢您的任何帮助
The @
symbol is called an "as-pattern". @
符号称为“原样”。 In the example above, you can use calc
to mean the whole record. 在上面的示例中,您可以使用calc
表示整个记录。 Usually you'd use it like this: calc@(MyResult someResult)
-- so you can have both the whole thing and the pieces that you're matching. 通常,您会这样使用它: calc@(MyResult someResult)
-这样您就可以拥有整个内容和您要匹配的部分。 You can do the same thing with lists ( myList@(myHead:myTail)
) or tuples ( myTuple@(myFst, mySnd)
. It's pretty handy! 您可以使用列表( myList@(myHead:myTail)
)或元组( myTuple@(myFst, mySnd)
。
MyResult{..}
uses RecordWildcards . MyResult{..}
使用RecordWildcards 。 Which is a neat extension! 这是一个很好的扩展! BUT RecordWildcards doesn't help you update just one field of a record. 但是RecordWildcards不能帮助您仅更新记录的一个字段。
You can do this instead: calc { theFieldYouWantToUpdate = somethingNew }
. 您可以改为: calc { theFieldYouWantToUpdate = somethingNew }
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.