(0) I want to reduce boilerplate code in the Elm files I write. I’m happy to put the boilerplate elsewhere, particularly if it’s in a file that can be automatically generated from the rest of the project.
I’m looking for references to prior art, alternative approaches, and also feedback. I’d be delighted if someone else has already discovered and implemented this idea. That would mean less work for me!
(1) My toy problem is to create a selector for RGB values. So I start my app with
type Msg = R | B | G
init = { red = 0, blue = 0, green = 0 }
You can see the whole implementation on Ellie https://ellie-app.com/cDdvYdnJXkca1.
(2) Here’s my update
method.
update msg state =
let
key = get_key msg
prev = key state
next = prev + 1
in
modify state key next
There’s no case
in update
. That’s hidden in get_key
. We use modify
to create the new state
.
(3) All this can be made to work with Elm 0.19. Here’s some crucial parts of the implementation.
get_key msg =
case msg of
R -> .red
B -> .blue
G -> .green
lookup =
{ red = \record value -> { record | red = value }
, blue = \record value -> { record | blue = value }
, green = \record value -> { record | green = value }
}
modify record key value =
key lookup record value
(4) Much of (3) can be generated automatically. In particular, lookup
needs only a list of all record keys in the app. And perhaps the get_key
function for Msg
can be similarly generated.