3.11

Let Expression

When someone else reads our escapeEarth function’s definition, they might wonder what the numbers 11.186 and 7.67 really mean.

escapeEarth velocity speed =
    if velocity > 11.186 then
        "Godspeed"
    else if speed == 7.67 then
        "Stay in orbit"
    else
        "Come back"

It would be nice if we could give them names. We can do that using a let expression. In Playground.elm, change escapeEarth so that it looks like this:

escapeEarth velocity speed =
    let
        escapeVelocityInKmPerSec =
            11.186

        orbitalSpeedInKmPerSec =
            7.67
    in
        if velocity > escapeVelocityInKmPerSec then
            "Godspeed"
        else if speed == orbitalSpeedInKmPerSec then
            "Stay in orbit"
        else
            "Come back"

let expression creates a local scope. Often times, we want to define local constants and functions that we don’t want the rest of the code in our application to know about. We can define them inside a let expression. They won’t be visible outside the scope created by a let expression making them essentially private. No code outside escapeEarth function can access the constants: escapeVelocityInKmPerSec and orbitalSpeedInKmPerSec.

Right now if a spaceship’s velocity or speed isn’t fast enough to either escape Earth’s gravity or stay in an orbit we simply tell it to come back to Earth. It would be more helpful if we could tell the spaceship where to land. Let’s create a function for that inside the let expression.

escapeEarth velocity speed fuelStatus =
    let
        escapeVelocityInKmPerSec =
            11.186

        orbitalSpeedInKmPerSec =
            7.67

        whereToLand fuelStatus =
            if fuelStatus == "low" then
                "Land on droneship"
            else
                "Land on launchpad"
    in
        if velocity > escapeVelocityInKmPerSec then
            "Godspeed"
        else if speed == orbitalSpeedInKmPerSec then
            "Stay in orbit"
        else
            whereToLand fuelStatus

escapeEarth function now takes an additional parameter called fuelStatus. The newly defined private function whereToLand checks the fuel status and tells where to land. This function is not visible outside of the let expression. Modify main to apply escapeEarth like this:

main =
    escapeEarth 10 6.7 "low"
        |> Html.text

If you refresh the page at http://localhost:8000/elm-examples/Playground.elm, you should see “Land on droneship”.

Back to top

New chapters are coming soon!

Sign up for the Elm Programming newsletter to get notified!

* indicates required
Close