Record with redundant data, bad idea?

Hi,

I have this type

type ExpensesSummary = { Count: int; Total: float; Average: float; Media: float}

which is not great (duplication of data, possible inconsistent data, …), as r.Average = f.Float / r.Count.

However, having the value available as r.Average would have the advantage to simplify the code displaying these values in a chart: all code would be displayable with the exact same code.

Any advice about this in F#?

Thanks!

1 Like

Maybe consider having ExpensesSummary type without duplication for backend and separate ViewModel type for displaying to user? Or you may add property to it, like this:

    type ExpensesSummary =
        { Count: int
          Total: float
          Media: float }
          with
                member m.AVerage = m.Total / (float m.Count)
2 Likes

Thanks @evgeny! I’m working in a Jupyter notebook, so I’m not planning on having 2 types, but your suggestion of adding a property seems exactly what I needed!

Seems pattern matching is not available with those members, as this is complaining about inexisting Average:

|> Seq.map (fun (_,{Total= total; Average=avg}) -> 

Is it specified somewhere? I didn’t see this mentioned in the docs I looked at.
As a workaround I do

|> Seq.map (fun (_,r) -> ... r.Total ... r.Average

Is there a better way I missed somehow?

Thanks

Unfortunately, you’re losing ability to pattern match here.

Note that properties are (IIRC) not stored / cached - so every time you hit that property it’ll recalculate it. Not necessarily a problem for simple properties but worth bearing in mind.

1 Like