2
votes

I try to make a function which take a record and a list of property names and return the values as a list of string:

Model -> (List String) -> (List String)

The goal is later to be able to render dynamically a record into an HTML table :

Model -> (List String) -> (Html Cmd)

I succeed to implement this:

import Html exposing (text)

type Field
  = FieldInt Int
  | FieldString String

type alias Model = 
  { name: Field
  , age: Field
  }

user1 = Model (FieldString "foo") (FieldInt 3)

field2text: Field -> String
field2text field =
  case field of
    FieldInt value ->
      toString value
    FieldString value ->
      value

updateModel: (List (a -> Field)) -> (List String)
model2values fns model =
  List.map (\fn -> field2text <| fn model) fns

main =
  text <| toString (model2values [.name, .age] user1)

How one would update the model2values function to be able to change the last line into:

main =
  text <| toString (model2values ["name", "age"] user1)
1

1 Answers

3
votes

There is no nice way, so you are left with:

toFieldGetter : String -> (a -> Field)
toFieldGetter : name = 
    case name of 
        "name" -> .name
        ...

model2values_ = model2values << List.map toFieldGetter

main =
  text <| toString (model2values_ ["name", "age"] user1)