通过点函数更新 Elm-lang 记录中的字段?

Update a field in an Elm-lang record via dot function?

是否可以通过函数(或其他方式)更新 Elm 记录中的字段而不明确指定精确的字段名称?

示例:

> fields = { a = 1, b = 2, c = 3 }
> updateField fields newVal fieldToUpdate = { fields | fieldToUpdate <- newVal }
> updateField fields 5 .a -- does not work

更新:

为了添加一些上下文,我正在尝试整理以下代码:

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 函数就太好了:

UpdatePhraseInput contents -> updateInput model contents .phrase
UpdatePointsInput contents -> updateInput model contents .points

滚动你自己的更新函数

是的,虽然可能不如从田地里得到好。但是思路是一样的,你写一个简单的使用记录更新语法的函数:

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)

Focus 图书馆

当您组合 fieldfieldSet 时,您会得到类似于 Focus 的内容。尽管该图书馆的用途不仅仅是记录。这是使用 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

理想情况下,您可以定义一个可以 select 更新哪个字段的函数,但您不能。

参见 This article,它解释了为什么目前无法在 elm 中功能性地更新记录中的字段:

"Seasoned functional programmers will surely have noticed that many of these concepts sound a lot like lenses, and Elm actually already has a lens-like library authored by Evan himself, called Focus. This, however, does not actually solve the problem: it requires manual description of setters just like the purely function based approach does."

...并且以下 comment from the the creator of Elm explaining why proposed support for this 未添加到最近对记录的更改中:

"I considered that and decided against it. I know that proposal. It's a language feature proposal, not a simple syntax thing"