转换键变量名中的字符串

Transform string in key variable name

存在将字符串转换为key的可能性,例如:

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

您将无法完全按照自己的意愿行事,因为那样无法访问记录。在你的情况下,我会推荐一本字典

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)