Search code examples
functional-programmingelm

"I got stuck while parsing the function definition:": How to properly define an Elm function?


I'm experiment/practicing Elm for the first time and am running into difficulty defining a function. The following:

isDivisible : Int -> Int -> Int -> Bool
isDivisible n x y =
  ((modBy n x) == 0) && ((modBy n y) == 0)

isDivisible 4 4 2

Results in:

-- PROBLEM IN DEFINITION --------------------------------------- Jump To Problem

I got stuck while parsing the `isDivisible` definition:

5| isDivisible 4 4 2
                    ^
I am not sure what is going wrong exactly, so here is a valid definition (with
an optional type annotation) for reference:

    greet : String -> String
    greet name =
      "Hello " ++ name ++ "!"

Try to use that format!

The Elm interpreter that CodeWars uses lets this pass through; it just says that the output is incorrect for some inputs (like 4 4 2). There are no Google results for "I got stuck while parsing the * definition:" (even though the parser is open-source, go figure). This is my first time in a functional language. What's wrong?


Solution

  • I'm not sure why your isDivisible function takes three numbers, but the syntax error you're seeing does not refer to its definition, but to your call:

    isDivisible 4 4 2
    

    In Elm, all your expressions (like the above) need to live within functions. You cannot simply write them at the top level of your file. They need to be used in a context where Elm knows what to do with them.

    Elm programs start executing from the main function. The main function might return different things depending on what you want to do, but the simplest use case is to return some HTML.

    module Main exposing (main)
    
    import Html exposing (text)
    
    
    main =
        text "Hello World"
    
    

    Run in ellie

    If you compile and open that in your browser, you'll see the text "Hello World" on the screen. Notice we placed our code under the main function, instead of writing them in the file directly.

    With that in mind, you could do something like the following to show the output of your call:

    main =
        if isDivisible 4 4 2 then
            text "It is divisible"
    
        else
            text "It is NOT divisible"
    

    Run in ellie

    If you just want to see the output of your call in the console instead, you can use the Debug.log function, like this:

    main =
        let
            _ =
                Debug.log "Is divisible?" (isDivisible 4 4 2)
        in
        text "Hello World"
    

    Run in Ellie (see LOGS)