Skip to content

Instantly share code, notes, and snippets.

@jbrains
Last active July 23, 2017 15:46
Show Gist options
  • Save jbrains/01625b04de92cfc96e4f0e08485d066c to your computer and use it in GitHub Desktop.
Save jbrains/01625b04de92cfc96e4f0e08485d066c to your computer and use it in GitHub Desktop.
Removing duplication with Elm record syntax
playerDetailsViewModel : (PlayerId -> Int) -> PlayerModel -> PlayerDetailsViewModel
playerDetailsViewModel playerPointsScored playerModel =
PlayerDetailsViewModel
playerModel.id
playerModel.name
(playerPointsScored playerModel.id)
playerDetailsViewModel : (PlayerId -> Int) -> PlayerModel -> PlayerDetailsViewModel
playerDetailsViewModel playerPointsScored { id, name } =
PlayerDetailsViewModel
id
name
(playerPointsScored id)
@jbrains
Copy link
Author

jbrains commented Jul 22, 2017

How do I remove duplication here in Elm? I have in mind something like

playerModel
  |> magic happens here
  |> PlayerDetailsViewModel

@nhajratw
Copy link

One might ask why you're creating a ViewModel to begin with ... could you just pass the PlayerModel to the view function and have the view function call playerPointsScored when needed?

@jbrains
Copy link
Author

jbrains commented Jul 22, 2017

@nhajratw I was there and I didn't like it. I've been pulling details up the call stack and I've ended up here.

@jbrains
Copy link
Author

jbrains commented Jul 22, 2017

Destructuring, duh. Not as cool as what I had in mind, but helpful all the same.

@Neppord
Copy link

Neppord commented Jul 23, 2017

From my expereience in both OOP but even stronger from my experience in FP: it is not a good idea to flatten data. Yes you should not let the called function or method go deep into your structure and do what it want either. Instead you should use functors and or other pattern to embellish the methods and functions so that they don't need to know about the wrapping structures.

It would be interesting to see the usage of the view-model. Right now it seams like it would be better of just being a pair (or any product type).

getScore model = model |> .id |> playerPointsScored
-- mapRight getScore (model, model) --
-- (model, model |> getScore ) --

or something like that. I wish to make getScore dot free but i dont know elm good enough for that. Now the renderer dont need to know how to render a pair just how to render models and scores and you can use mapBoth to get both outputs and combine them later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment