Stream: beginners

Topic: ✔ namespacing a type and utility functions within a module?


view this post on Zulip Mo (Dec 12 2024 at 20:44):

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?

view this post on Zulip lue (Dec 12 2024 at 20:52):

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

view this post on Zulip Mo (Dec 12 2024 at 20:53):

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.

view this post on Zulip Mo (Dec 12 2024 at 20:54):

lue said:

It also allows you to also choose more intuitive names sometimes like urlToState vs State.fromUrl

That's a good point too.

view this post on Zulip Brendan Hansknecht (Dec 12 2024 at 21:33):

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

view this post on Zulip Brendan Hansknecht (Dec 12 2024 at 21:34):

In practice, I tend to either stateInit, stateUpdate, ..., or I have modules for specific types

view this post on Zulip Notification Bot (Dec 13 2024 at 01:50):

Mo has marked this topic as resolved.


Last updated: Jul 06 2025 at 12:14 UTC