转换键变量名称中的字符串

问题描述 投票:2回答:1

可以将字符串转换为键,例如:

type alias Model =
  { sun : Int  -- Init with 0
  , moon : Int -- Init with 0
  }

我想要实现的目标:

let
  userSelect = "sun";
in
 ({ model | userSelect = 1 }, Cmd.none)  -- ugly to be easy to understand 

在model.sun之后应该1

elm
1个回答
4
投票

由于访问记录不起作用,您将无法完全按照自己的意愿行事。在你的情况下,我会推荐一个字典

type alias Model =
  { planets : Dict String Int
  }


planets = 
    Dict.fromList 
        [ ("sun", 0)
        , ("moon": 0)
        ]
model = { planets = planets }

然后

let
  userSelect = "sun";
in
 ({ model | planets = Dict.insert userSelect 1 model.planets }, Cmd.none)
© www.soinside.com 2019 - 2024. All rights reserved.