Elm Syntax question: If and else inside the "let in" scope

Hi,

I’m not sure how to use the syntax for if and else inside the “let” scope in Elm.

What doesn’t work is the below code.

backgroundRect : Int -> Svg msg
backgroundRect v =
    let
        color = "red"
           
        m = modBy 2 v
        if m == 0 then
           color = "green"
       else
           color = "blue"
    in
      Svg.rect
          [ width "100%"
          , height "100%"
          , fill color
          ]
          []


As a work around I’m doing this, which is ugly. Any inputs on how to use “if and else inside the let and in block?”

backgroundRect : Int -> Svg msg
backgroundRect v =
    let
        color = "red"   
        m = modBy 2 v
    in

    if m == 0 then
      Svg.rect
          [ width "100%"
          , height "100%"
          , fill "Green"
          ]
          []
   else 
      Svg.rect
          [ width "100%"
          , height "100%"
          , fill "red"
          ]
          []

  

Best,
SantMan

I think you’re confusing if statements with if expressions. Unlike in Javascript, Python, and similar languages in Elm an if .. else returns a value. Additionally, color in your code is immutable. So when you write

if m == 0 then
    color = "green"
else
    color = "blue"

you’re attempting to mutate color which won’t be allowed. You likely want something like

backgroundRect v =
    let
        color = 
            if m == 0 then
                "green"
            else
                "blue"

        m = modBy 2 v
    in
3 Likes

“If” expressions return a value, unlike in C where they only take an action. So you can do:

    let
        m = modBy 2 v
        color =
            if m == 0 then
                "green"

            else
                "blue"
    in
2 Likes

Thank you @wolfadex and @progger for your response and explaination. I understood the syntax now.

Elm Error message was not so helpful in this case it was complaining about the let block and I couldn’t figure out what it is pointing at. Hope this could be improved in the near future.

2 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.