Search code examples
if-statementelmread-eval-print-loop

Elm - Executing multiple lines per if branch


For example, in one branch, I want see how many times a number is divisible by 1000, then pass the starting number less that amount into the function recursively. This is what I have written:

if num // 1000 > 0 then
    repeat (num // 1000) (String.fromChar 'M')
    convertToRom (num % 1000)

However, I get the following error in the REPL when testing:

> getRomNums 3500
-- TYPE MISMATCH ----------------------------------------- .\.\RomanNumerals.elm

Function `repeat` is expecting 2 arguments, but was given 4.

34|             repeat (num // 1000) (String.fromChar 'M')
35|>            convertToRom (num % 1000)

Maybe you forgot some parentheses? Or a comma?

How can I write multiple lines of code for a single if branch?

Unrelated side note: The format system makes the double slash a comment, but in Elm the double slash is integer division. Not sure how to fix that.


Solution

  • In Elm (and other functional languages like Haskell), you don't write code in iterative steps like you do in imperative languages. Every function has to return a value, and every branch of logic has to return a value. There is no single answer around how to "do multiple things" in Elm but with Elm's type system, tuples, and recursion, you'll find that the lack of imperative doesn't really hold you back from anything. It's just a paradigm shift from writing code in an imperative style.

    For your purposes of writing a roman numeral conversion function, I think an immediate answer lies in using explicit recursion and string concatenation on the result:

    convertToRom : Int -> String
    convertToRom num =
        if num // 1000 > 0 then
            String.repeat (num // 1000) (String.fromChar 'M') ++ convertToRom (num % 1000)
        else if ...
        else
            ""
    

    As you grow your functional programming toolset, you'll find yourself explicitly using recursion less and less and relying on higher levels of abstraction like folds and maps.