Search code examples
elm

Can you use a string for record access in elm?


If I have a string that looks like the name of a field in a record, can I use it to get the data somehow? Something like :

."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"]

Solution

  • Not the way you want it but you can have a function that pattern matches on a string to access a part of a record. You need to be explicit about what it should do in case you give it something invalid.

    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