问题描述
是否可以通过函数(或其他方式)更新Elm记录中的字段而无需显式指定确切的字段名称?
Is it possible to update a field in an Elm record via a function (or some other way) without explicitly specifying the precise field name?
示例:
> fields = { a = 1, b = 2, c = 3 }
> updateField fields newVal fieldToUpdate = { fields | fieldToUpdate <- newVal }
> updateField fields 5 .a -- does not work
UPDATE:
要添加一些上下文,我试图干燥以下代码:
UPDATE:
To add some context, I'm trying to DRY up the following code:
UpdatePhraseInput contents ->
let currentInputFields = model.inputFields
in { model | inputFields <- { currentInputFields | phrase <- contents }}
UpdatePointsInput contents ->
let currentInputFields = model.inputFields
in { model | inputFields <- { currentInputFields | points <- contents }}
如果我可以叫神话般的 updateInput
函数是这样的:
Would be really nice if I could call a mythical updateInput
function like this:
UpdatePhraseInput contents -> updateInput model contents .phrase
UpdatePointsInput contents -> updateInput model contents .points
推荐答案
滚动您自己的更新功能
是的,尽管可能不如从字段中获取 。但是想法是相同的,您编写了一个仅使用记录更新语法的函数:
Rolling your own update function
Yes, though perhaps not as nicely as getting from a field. But the idea is the same, you write a function that simply uses the record update syntax:
setPhrase r v = { r | phrase <- v }
setPoints r v = { r | points <- v }
updInputFields r f = { r | inputFields <- f r.inputFields }
然后您可以编写:
UpdatePhraseInput contents -> updInputFields model (flip setPhrase contents)
UpdatePointsInput contents -> updInputFields model (flip setPoints contents)
焦点
库
当您组合 field
和 fieldSet
时,您会得到类似。尽管该库不仅可以处理记录,还可以处理更多的事情。这是使用 Focus
的示例:
The Focus
library
When you combine field
and fieldSet
, you get something like a Focus
. Although that library works for more things than just records. Here's an example of what this would look like using Focus
:
phrase = Focus.create .phrase (\upd r -> { r | phrase <- upd r.phrase })
points = Focus.create .points (\upd r -> { r | points <- upd r.points })
inputFields = Focus.create .inputFields (\upd r -> { r | inputFields <- upd r.inputFields})
然后您可以编写:
UpdatePhraseInput contents -> Focus.set (inputFields => phrase) contents model
UpdatePointsInput contents -> Focus.set (inputFields => points) contents model
这篇关于通过点函数更新Elm-lang记录中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!