Switch in Idris
Here’s the translation of the given code into Idris along with an explanation.
Switch statements express conditionals across many branches.
module Main
import Data.Time
main : IO ()
main = do
let i = 2
putStr("Write " ++ show i ++ " as ")
case i of
1 => putStrLn "one"
2 => putStrLn "two"
3 => putStrLn "three"
_ => pure ()
-- Using multiple expressions in the same case statement and a default case
currentTime <- getCurrentTime
let weekday = dayOfWeek (toCalendarTime (UTCTime currentTime))
case weekday of
Saturday, Sunday => putStrLn "It's the weekend"
_ => putStrLn "It's a weekday"
-- Switch without an expression, using non-constant expressions in case statements
let hour = timeOfDayHour (timeToTimeOfDay (utctDayTime currentTime))
case () of
_ | hour < 12 => putStrLn "It's before noon"
_ => putStrLn "It's after noon"
-- Type switch to determine the type of an interface value
whatAmI : (input : Type) -> IO ()
whatAmI t = case t of
Bool t => putStrLn "I'm a bool"
Int t => putStrLn "I'm an int"
_ => putStrLn ("Don't know type " ++ show t)
whatAmI True
whatAmI 1
whatAmI "hey"
Here’s a basic case
.
let i = 2
putStr("Write " ++ show i ++ " as ")
case i of
1 => putStrLn "one"
2 => putStrLn "two"
3 => putStrLn "three"
_ => pure ()
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 <- getCurrentTime
let weekday = dayOfWeek (toCalendarTime (UTCTime currentTime))
case weekday of
Saturday, Sunday => putStrLn "It's the weekend"
_ => putStrLn "It's a weekday"
case
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 hour = timeOfDayHour (timeToTimeOfDay (utctDayTime currentTime))
case () of
_ | hour < 12 => putStrLn "It's before noon"
_ => putStrLn "It's after noon"
A type case
compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable t
will have the type corresponding to its clause.
whatAmI : (input : Type) -> IO ()
whatAmI t = case t of
Bool t => putStrLn "I'm a bool"
Int t => putStrLn "I'm an int"
_ => putStrLn ("Don't know type " ++ show t)
whatAmI True
whatAmI 1
whatAmI "hey"
Running the code will produce the expected outputs based on the conditions specified.