If Else in Elm
Branching with if
and else
in Elm is straightforward, but with some key differences from imperative languages.
import Html exposing (Html, div, text)
main : Html msg
main =
div []
[ -- Here's a basic example.
if modBy 2 7 == 0 then
text "7 is even"
else
text "7 is odd"
-- You can have an `if` expression without an else.
, if modBy 4 8 == 0 then
text "8 is divisible by 4"
else
text ""
-- Logical operators like `&&` and `||` are often useful in conditions.
, if modBy 2 8 == 0 || modBy 2 7 == 0 then
text "either 8 or 7 are even"
else
text ""
-- In Elm, you can't declare variables inside conditions.
-- Instead, you can use let expressions for local bindings.
, let
num = 9
in
if num < 0 then
text (String.fromInt num ++ " is negative")
else if num < 10 then
text (String.fromInt num ++ " has 1 digit")
else
text (String.fromInt num ++ " has multiple digits")
]
In Elm, if
is an expression that always returns a value, not a statement. This means you always need an else
branch, and both branches must return the same type of value.
Note that you don’t need parentheses around conditions in Elm, similar to other functional languages. The structure is if condition then result else alternative
.
To run this Elm code, you would typically compile it to JavaScript and run it in a browser. The output would be rendered as HTML.
Elm doesn’t have a direct equivalent to Go’s ability to declare variables in if statements. Instead, you can use let
expressions for local bindings when needed.
There is no ternary operator in Elm, as the if
expression already serves this purpose concisely.
Remember that Elm is a functional language, so the approach to conditional logic is somewhat different from imperative languages. Every expression must return a value, and there are no side effects in these conditional expressions.