How to convert a record of strings to floats in elm

Viewed 39

I have a record that is supplied by the user:

type alias Model =
  { age : String,
    weight : String,
    height : String,
    appetite : String
  }

I want to convert it to numbers:

type alias FloatModel =
  { age : Float,
    weight : Float,
    height : Float,
    appetite : Float
  }

My struggle is that String.toFloat might return Nothing if the user entered bad data. So I guess I want a Maybe FloatModel to handle bad data. How can I call String.toFloat on each member, and if they're all successful return Just FloatModel and if not return Nothing?

1 Answers

If you want to retain the integrity of FloatModel, so that all fields are Float values, you could have a function which takes a Model and returns a Maybe FloatModel, which succeeds only when all fields can be parsed.

This could be done by mapping over each of the fields, so that a single failure will "bubble up" and cause the function to return Nothing.

deserializeModel : Model -> Maybe FloatModel
deserializeModel { age, weight, height, appetite } =
    Maybe.map4 FloatModel
        (String.toFloat age)
        (String.toFloat weight)
        (String.toFloat height)
        (String.toFloat appetite)
Related