Say I have a module that provides some functionality. The implementation uses a record and several functions that act on the record. What is the best way to organise that code?
I could create a separate module file for the record and its functions, but that puts it "too far" from the core functionality in the main module. I'd prefer to keep the 10 lines or so in the main module file.
I could use some naming conventions to prefix the support functions, but that gets wordy.
State : { ... }
stateInit : Args -> State
stateReset: State -> State
stateIncr: State -> State
# etc...
Ideally I'd like to associate those functions with State, to call them like State.init
, State.reset
, etc., without creating a separate module file.
I saw another suggestion from Brendan Hansknecht a year ago which embeds functions in a def, like this:
State : { ... }
state =
init = \args -> { ... }
reset = \s -> ...
incr = \s -> ...
{ init, reset, incr }
which is a good compromise, except I lose the capitalisation, and I take up a good parameter name state
.
Are there other good options?
I pretty much always go for the first
State : { ... }
stateInit : Args -> State
stateIncr: State -> State
It also allows you to also choose more intuitive names sometimes like urlToState
vs State.fromUrl
or listMapAndStatesCombine
vs State.combineAfterMapping
or whatever
I can live with:
State : { ... }
mState =
init = \args -> { ... }
reset = \s -> ...
incr = \s -> ...
{ init, reset, incr }
which makes refactoring into an external module easy, if it becomes necessary.
I'm curious also if the compiler will as easily be able to optimise functions declared this way.
lue said:
It also allows you to also choose more intuitive names sometimes like
urlToState
vsState.fromUrl
That's a good point too.
I'm curious also if the compiler will as easily be able to optimise functions declared this way.
I would have to double check, but I'm pretty sure it will optimize the same as long as there are no captures
In practice, I tend to either stateInit
, stateUpdate
, ..., or I have modules for specific types
Mo has marked this topic as resolved.
Last updated: Jul 06 2025 at 12:14 UTC