What exactly is the 'Program' in elm programs?

I’m new to elm and I’m currently trying to read the official examples.
When I came across Browser.sandbox, the elmtooling in vscode told me its definition:

sandbox :
{ init : model
, view : model -> Html msg 
, update : msg -> model -> model
-> Program () model msg

I guess the image of sandbox is a partial function of Program, where two slots have already been filled, requiring only one argument to be given (which I suppose is the ‘flag’)
Then I wondered what the ‘Program’ means. I was then told by the editor that ‘Program’ describes an elm program (sounds fairly reasonable). What really made me confused is the following line:

type Program flag model msg = Program

Can someone help me understand this line? How can this line be parsed?

1 Like

Hello and welcome to Elm. :slight_smile:

I’m not good at explaining the sandbox, but as for Program: Definitions like this in core packages generally mean that the type is implemented internally by the compiler and there is no definition for it in Elm syntax.

Parsed literally

type SomeType = SomeType

means that SomeType is a unit type with only a single possible value: SomeType

Adding some type parameters to type definition like with Program

type OtherType a b c = OtherType

still means that it’s a unit type.

While there are uses for unit types, it doesn’t make any sense for Program to be one, and it isn’t. It’s just a custom to define internally implemented types like Program as unit types.

What you see here is a phantom type, a type whose type parameters do not appear on the right side of the definition. This is useful when you want to ensure type safety.

The actual implementation of a Program is a black box. It is implemented by the runtime in JS.

Elm has a private API (available only for core packages) that allows the implementation of things in JS that are trusted by the compiler. So, if the sandbox private implementation says that it has a type of Program () model msg the compiler trusts it without needing to go check the implementation.

You will find this pattern of using phantom types for types that are implemented in JS. Cmd, Sub and Task, are also implemented as phantom unit types. :wink:

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.