Switch in PureScript

Here’s how to translate the provided code example to PureScript:

Switch Statements

Switch statements express conditionals across many branches.

module Main where

import Prelude
import Effect (Effect)
import Effect.Console (log)
import Data.Time (now, weekday, DayOfWeek(..))

main :: Effect Unit
main = do
  -- Here’s a basic `switch`.
  let i = 2
  log $ "Write " <> show i <> " as "
  case i of
    1 -> log "one"
    2 -> log "two"
    3 -> log "three"
    _ -> pure unit

  -- You can use commas to separate multiple expressions in the same `case` statement.
  -- We use the optional `default` case in this example as well.
  currentTime <- now
  let currentDay = weekday currentTime
  case currentDay of
    Saturday -> log "It's the weekend"
    Sunday -> log "It's the weekend"
    _ -> log "It's a weekday"

  -- `switch` without an expression is an alternate way to express if/else logic.
  -- Here we also show how the `case` expressions can be non-constants.
  let currentHour = currentTime.hour
  case currentHour of
    hour | hour < 12 -> log "It's before noon"
    _ -> log "It's after noon"

  -- A type `switch` compares types instead of values. 
  -- You can use this to discover the type of a value.
  let whatAmI i =
        case i of
          _ :: Boolean -> log "I'm a bool"
          _ :: Int -> log "I'm an int"
          _ -> log $ "Don't know type " <> show i
  whatAmI (true :: Boolean)
  whatAmI (1 :: Int)
  whatAmI ("hey" :: String)

To run the program, ensure you have PureScript and Spago installed, and follow these steps:

  1. Place the code in Main.purs.
  2. In your project directory, install the necessary dependencies:
    spago install
  3. Build and run the program using:
    spago run

You should see the output as:

Write 2 as 
two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type "hey"

Let’s learn more about PureScript!