Recursion in Elm

module Main exposing (main)

import Html exposing (Html, div, text)


-- This `fact` function calls itself until it reaches the
-- base case of `fact 0`.
fact : Int -> Int
fact n =
    if n == 0 then
        1

    else
        n * fact (n - 1)


-- In Elm, we don't have a direct equivalent of closures as in Go.
-- Instead, we can define a recursive function directly.
fib : Int -> Int
fib n =
    if n < 2 then
        n

    else
        fib (n - 1) + fib (n - 2)


main : Html msg
main =
    div []
        [ text ("Factorial of 7: " ++ String.fromInt (fact 7))
        , Html.br [] []
        , text ("Fibonacci of 7: " ++ String.fromInt (fib 7))
        ]

This Elm code demonstrates recursion using two classic examples: factorial and Fibonacci sequence.

The fact function is a direct translation of the factorial function from the original example. It recursively calls itself until it reaches the base case of fact 0.

In Elm, we don’t have closures in the same way as in the original example. Instead, we define the Fibonacci function fib directly as a recursive function. It follows the same logic as the original closure-based implementation.

The main function creates an HTML structure to display the results of both recursive functions for the input 7.

To run this Elm program:

  1. Save the code in a file named Main.elm.
  2. Use the Elm compiler to compile it: elm make Main.elm --output=main.js.
  3. Create an HTML file that includes the compiled JavaScript and add a target div:
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Recursion in Elm</title>
    <script src="main.js"></script>
</head>
<body>
    <div id="elm"></div>
    <script>
        var app = Elm.Main.init({
            node: document.getElementById('elm')
        });
    </script>
</body>
</html>
  1. Open this HTML file in a web browser to see the output.

The output will display:

Factorial of 7: 5040
Fibonacci of 7: 13

This example demonstrates how recursion works in Elm, showing both a simple recursive function (factorial) and a more complex one (Fibonacci). The syntax and structure are different from the original, but the core concepts of recursion remain the same.