你可以在elm中使用字符串进行记录访问吗?

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

如果我有一个看起来像记录中字段名称的字符串,我可以用它以某种方式获取数据吗?就像是 :

."name".toKey bill 
bill.(asSymbol "name")

-

song =
  { title = "foot", artist = "barf", number = "13" }

fieldsILike : List String
fieldsILike =
  [ "title", "artist" ]


val song key =
  .key song

foo = List.map (val song) fieldsILike --> should be ["foot", "barf"]
elm
2个回答
4
投票

不是你想要的方式,但你可以有一个函数,模式匹配字符串以访问记录的一部分。如果你给它一些无效的东西,你需要明确它应该做什么。

import Html exposing (..) 

type alias Song = { artist : String, number : String, title : String }

song : Song
song =
  { title = "foot", artist = "barf", number = "13" }

fieldsILike : List String
fieldsILike =
  [ "title", "artist" ]


k2acc : String -> (Song -> String)
k2acc key = 
  case key of 
  "title" ->  .title
  "artist" -> .artist
  "number" -> .number
  _ ->  always ""

val : Song -> String -> String
val = flip k2acc 
-- `flip` was removed in elm 0.19, so you'll need to 
-- do something like the following going forward: 
-- val song field = (k2acc field) song   

foo = List.map (val song) fieldsILike

main = text <| toString foo

4
投票

不,但你可以使用Dict

import Dict exposing (get ,fromList)

song = fromList [ ("title", "foot"), ("artist", "barf") ]

get "title" song -- Just "foot"
get "artist" song -- Just "barf"
get "test" song  -- Nothing
© www.soinside.com 2019 - 2024. All rights reserved.