代码之家  ›  专栏  ›  技术社区  ›  Guilherme Escarabel

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

elm
  •  2
  • Guilherme Escarabel  · 技术社区  · 7 年前

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

    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 
    

    型号之后。太阳应该1

    1 回复  |  直到 7 年前
        1
  •  4
  •   Simon H    7 年前

    您将无法完全按照自己的意愿进行操作,因为访问记录的方式无法做到这一点。对你来说,我建议你买一本字典

    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)