View Category

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
scala
val name = "Bob"
if (name.equals("Bob")) printf("Hello, %s!\n", name)
val name = "Bob"

// Scala supports operator overloading, so the following works correctly
if (name == "Bob") printf("Hello, %s!\n", name)
erlang
if (Name == "Bob") -> io:format("Hello, ~s!~n", [Name]) ; true -> false end.
case Name of "Bob" -> io:format("Hello, ~s!~n", [Name]) ; _ -> false end.
Name == "Bob" andalso (begin io:format("Hello, ~s!~n", [Name]), true end).

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
scala
val age = 42
if (age > 42) println("You are old") else println("You are young")
println( "You are " + ( if ( age > 42 ) "old" else "young" ) )
erlang
if Age > 42 -> io:format("You are old~n") ; true -> io:format("You are young~n") end.
Message = if Age > 42 -> "old" ; true -> "young" end, io:format("You are ~s~n", [Message]).
case Age > 42 of true -> io:format("You are old~n") ; false -> io:format("You are young~n") end.
case Age of _ when Age > 42 -> io:format("You are old~n") ; _ -> io:format("You are young~n") end.
Message = case Age of _ when Age > 42 -> "old" ; _ -> "young" end, io:format("You are ~s~n", [Message]).
Age > 42 andalso (begin io:format("You are old~n"), true end) orelse (begin io:format("You are young~n"), true end).
(fun (X) when X > 42 -> io:format("You are old~n"); (_) -> io:format("You are young~n") end)(Age).
(fun () when Age > 42 -> io:format("You are old~n"); () -> io:format("You are young~n") end)().
io:format("You are ~s~n", [if Age > 42 -> "old" ; true -> "young" end]).

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

scala
val age = 65

if (age > 84) println("You are really ancient")
else if (age > 30) println("You are middle-aged")
else println("You are young")
erlang
if
Age > 84 -> io:format("You are really ancient~n");
Age > 30 -> io:format("You are middle-aged~n");
true -> io:format("You are young~n")
end.
case Age of
_ when Age > 84 -> io:format("You are really ancient~n");
_ when Age > 30 -> io:format("You are middle-aged~n");
true -> io:format("You are young~n")
end.

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
scala
object FourToTwenties {
def unapply (n: Int) = (4 to 20).contains(n % 100)
}

def suffix (n: Int) = {
n match {
case FourToTwenties() => "th"
case n if n % 10 == 1 => "st"
case n if n % 10 == 2 => "nd"
case n if n % 10 == 3 => "rd"
case _ => "th"
}
}

for (n <- 1 to 40) {
println(n.toString + suffix(n))
}

erlang
Suffix = case Num of
N when N > 10, N < 20 -> "th";
N when N rem 10 =:= 1 -> "st";
N when N rem 10 =:= 2 -> "nd";
N when N rem 10 =:= 3 -> "rd";
_ -> "th"
end,
io_lib:format("~w~s", [Num, Suffix])

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
scala
var x = 1 ; while (x < 150) { printf("%d,", x) ; x *= 2 }
erlang
X = 1, print_while_X_less_150(X).
Pred = fun (X) -> X < 150 end,
Action = fun (X) -> io:format("~B,", [X]), X * 2 end,
X = 1,

while_do(Pred, Action, X).

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
scala
val dice = new GenRandInt(1, 6) ; var rnd = 0 ; var fmt = ""
do { rnd = dice.next ; fmt = if (rnd != 6) "%d," else "%d" ; printf(fmt, rnd) } while (rnd != 6)
erlang
Pred = fun (DiceRoll) -> DiceRoll =/= 6 end,
Action = fun (DiceRoll) -> io:format("~B,", [DiceRoll]), dice_roll() end,

do_while(Pred, Action, dice_roll()).
-module(dice).
-export([start/0]).

start() ->
roll(dice_roll()).

roll(6) ->
io:format("6~n", []);
roll(N) ->
io:format("~B,", [N]),
roll(dice_roll()).

dice_roll() -> random:uniform(6).

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
scala
// Using overloaded '*' operator (String-specific)
print("Hello" * 5)
List.range(0, 5) foreach { (_) => print("Hello") }
for (_ <- List.range(0, 5)) print("Hello")
// Lazy version
for (_ <- Stream.range(0, 5)) print("Hello")
dotimes(5, _ => print("Hello"))
(0 until 5) foreach { (_) => print("Hello") }
5 times { print("Hello") }
erlang
dotimes(5, fun () -> io:format("Hello") end).
lists:foreach(fun (_) -> io:format("Hello") end, lists:seq(1, 5)).

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
scala
for (i <- List.range(1, 11).reverse) printf("%d .. ", i) ; println("Liftoff!")
for (i <- List.range(-10, 0)) printf("%d .. ", (-i)) ; println("Liftoff!")
var i = 10 ; while (i > 0) { printf("%d .. ", i) ; i -= 1 } ; println("Liftoff!")
for (i <- -10 to -1) printf("%d .. ", (-i)) ; println("Liftoff!")
erlang
fromto(10, 1, -1, fun (X) -> io:format("~B .. ", [X]) end), io:format("Liftoff!~n").
lists:foreach(fun (X) -> io:format("~B .. ", [X]) end, lists:seq(10, 1, -1)), io:format("Liftoff!~n").