Loading search index…
No recent searches
No results for "Query here"
Here’s a basic switch.
switch
defmodule SwitchExample do def main do i = 2 IO.write("Write #{i} as ") case i do 1 -> IO.puts("one") 2 -> IO.puts("two") 3 -> IO.puts("three") end case :calendar.day_of_the_week(:calendar.local_time()) do 7 -> IO.puts("It's the weekend") 1 -> IO.puts("It's the weekend") _ -> IO.puts("It's a weekday") end case :calendar.local_time() |> elem(0) |> elem(2) do h when h < 12 -> IO.puts("It's before noon") _ -> IO.puts("It's after noon") end what_am_i(true) what_am_i(1) what_am_i("hey") end defp what_am_i(i) do case i do _ when is_boolean(i) -> IO.puts("I'm a bool") _ when is_integer(i) -> IO.puts("I'm an int") _ -> IO.puts("Don't know type #{inspect(i)}") end end end SwitchExample.main()
To run the program, put the code in switch_example.exs and use the elixir command.
switch_example.exs
elixir
$ elixir switch_example.exs 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 now learn more about the switch-like constructs and how we can use them in the Elixir language.