If Else in PureScript

Our first example demonstrates branching with if and else in PureScript. This is straightforward and similar to many other programming languages.

module Main where

import Prelude
import Effect (Effect)
import Effect.Console (log)

main :: Effect Unit
main = do
  -- Here's a basic example.
  if 7 `mod` 2 == 0
    then log "7 is even"
    else log "7 is odd"

  -- You can have an `if` statement without an else.
  if 8 `mod` 4 == 0
    then log "8 is divisible by 4"
    else pure unit

  -- Logical operators like `&&` and `||` are often useful in conditions.
  if 8 `mod` 2 == 0 || 7 `mod` 2 == 0
    then log "either 8 or 7 are even"
    else pure unit

  -- In PureScript, we can use `let` to declare variables in a local scope.
  -- These variables are available in the current and subsequent branches.
  let num = 9
  if num < 0
    then log $ show num <> " is negative"
    else if num < 10
      then log $ show num <> " has 1 digit"
      else log $ show num <> " has multiple digits"

To run this program, you would typically compile it with the PureScript compiler and then execute it with Node.js:

$ pulp run
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in PureScript, you don’t need parentheses around conditions, but you do need to use then and else keywords. The do notation is used for sequencing effects, which is necessary when working with Effect actions like logging to the console.

PureScript doesn’t have a direct equivalent to Go’s statement preceding conditionals, but we can achieve similar functionality using let bindings within a do block.

Also, PureScript doesn’t have a ternary operator, so you’ll need to use full if-then-else expressions even for basic conditions.