Search code examples
syntax-errorelm

Multiple statements in Main module


How do you put multiple lines of statements inside an Elm main module

Example,

module Main exposing (main)
import Html exposing (text)

main =
  text "1"
  text "2"

The above does not work and gives this error

Detected errors in 1 module.
-- TOO MANY ARGS -------------------------------------------------- src/Main.elm

The `text` function expects 1 argument, but it got 3 instead.

5|>  text "1"
6|   text "2"

Are there any missing commas? Or missing parentheses?

Putting parenthesis and commas does not help.


Solution

  • Elm is an expression-based language. It doesn't have statements because it doesn't have side-effects. Instead it consists of expressions which return values associated with types that are verified at compile-time.

    Your code is a valid expression syntactically, so I'm not sure how you got that specific error. I can't reproduce it either directly at top level, where expressions don't belong, or in a function where expressions do belong, but there I get a type error instead of a syntax error. You're leaving out some essential part of your code.

    In any case, even if you put it correctly into a function this won't do what you want. There are multiple problems even then:

    1. Your code will be interpreted as three arguments applied to the function text, '1', text, and '2', because the line-break is not significant.

    2. '1' is a character literal, not a string literal. "1" is a string literal.

    3. Whatever you're going to use this with, it most likely expects a single element, not a list of elements.

    The correct way to return two elements as one is to wrap the two elements in a parent element, like 'span' for example:

    module Main exposing (main)
    
    import Html exposing (text, span)
    
    main =
        span []
            [ text "1"
            , text "2"
            ]
    

    Lastly, I recommend that you begin learning by following the official Elm guide. Elm is different enough that a trial-and-error approach based on what tends to work in JavaScript is likely to just lead to frustration.