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.
python
if name == 'Bob':
print 'Hello, Bob!'
print 'Hello, Bob!'
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).
clojure
(def person "Bob")
(if (= person "Bob")
(println "Hello, Bob!"))
(if (= person "Bob")
(println "Hello, Bob!"))
fantom
if (name=="Bob") echo("Hello, Bob!")
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"
python
if age > 42:
print 'You are old'
else:
print 'You are young'
print 'You are old'
else:
print 'You are young'
print age > 42 and 'You are old' or 'You are 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]).
clojure
(def age 41)
(if (> age 42) "You are old" "You are young")
(if (> age 42) "You are old" "You are young")
fantom
if (age > 42)
echo("You are old")
else
echo("You are young")
echo("You are old")
else
echo("You are young")
echo((age > 42) ? "You are old" : "You are young")
Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)
python
if age > 84:
print 'You are really ancient'
elif age > 30:
print 'You are middle-aged'
else:
print 'You are young'
print 'You are really ancient'
elif age > 30:
print 'You are middle-aged'
else:
print '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.
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.
_ 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.
clojure
(println
(condp <= age
84 "You are really ancient"
30 "You are middle aged"
"You are young"))
(condp <= age
84 "You are really ancient"
30 "You are middle aged"
"You are young"))
fantom
if (age > 84)
echo("You are really ancient")
else if (age > 30)
echo("You are middle-aged")
else
echo("You are young")
echo("You are really ancient")
else if (age > 30)
echo("You are middle-aged")
else
echo("You are young")
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
python
def affix(num):
num = num == 1 and str(num) + 'st' or num == 2 and str(num) + 'nd' or \
num == 3 and str(num) +'rd' or str(num) + 'th'
return num
print [affix(x) for x in xrange(1,41)]
num = num == 1 and str(num) + 'st' or num == 2 and str(num) + 'nd' or \
num == 3 and str(num) +'rd' or str(num) + 'th'
return num
print [affix(x) for x in xrange(1,41)]
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])
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])
clojure
(def n 112)
(println (str n
(let [rem (mod n 100)]
(if (and (>= rem 11) (<= rem 13))
"th"
(condp = (mod n 10)
1 "st"
2 "nd"
3 "rd"
"th")))))
(println (str n
(let [rem (mod n 100)]
(if (and (>= rem 11) (<= rem 13))
"th"
(condp = (mod n 10)
1 "st"
2 "nd"
3 "rd"
"th")))))
fantom
suffix := |Int n -> Str|
{
if ((4..20).contains(n % 100))
return "th"
switch((n.toStr)[-1])
{
case '1': return "st"
case '2': return "nd"
case '3': return "rd"
default: return "th"
}
}
(1..40).each { echo("$it${suffix(it)}") }
{
if ((4..20).contains(n % 100))
return "th"
switch((n.toStr)[-1])
{
case '1': return "st"
case '2': return "nd"
case '3': return "rd"
default: return "th"
}
}
(1..40).each { echo("$it${suffix(it)}") }
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.
python
x = 1
while x < 150:
print '%s, ' % x,
x *= 2
while x < 150:
print '%s, ' % 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).
Action = fun (X) -> io:format("~B,", [X]), X * 2 end,
X = 1,
while_do(Pred, Action, X).
clojure
(take-while #(< % 150) (iterate #(* 2 %) 1))
fantom
x := 1
while (x < 150) {
Env.cur.out.print("$x,")
x *= 2
}
echo
while (x < 150) {
Env.cur.out.print("$x,")
x *= 2
}
echo
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"
python
import random, itertools
def dice():
while True:
yield random.randint(1,6)
print ", ".join(str(d) for d in itertools.takewhile(lambda x: x < 6, dice()))
def dice():
while True:
yield random.randint(1,6)
print ", ".join(str(d) for d in itertools.takewhile(lambda x: x < 6, dice()))
erlang
Pred = fun (DiceRoll) -> DiceRoll =/= 6 end,
Action = fun (DiceRoll) -> io:format("~B,", [DiceRoll]), dice_roll() end,
do_while(Pred, Action, dice_roll()).
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).
-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).
clojure
(loop [r (rand-int 6)]
(if (= r 5)
nil
(do
(println r)
(recur (rand-int 6)))))
(if (= r 5)
nil
(do
(println r)
(recur (rand-int 6)))))
fantom
rnd := 0
while(rnd != 6) {
rnd = Int.random(1..6)
Env.cur.out.print(rnd)
if (rnd != 6)
Env.cur.out.print(",")
}
echo
while(rnd != 6) {
rnd = Int.random(1..6)
Env.cur.out.print(rnd)
if (rnd != 6)
Env.cur.out.print(",")
}
echo
Perform an action a fixed number of times (FOR)
Display the string
"Hello" five times like "HelloHelloHelloHelloHello"
python
print "Hello" * 5
for i in range(5):
print "Hello"
print "Hello"
erlang
dotimes(5, fun () -> io:format("Hello") end).
lists:foreach(fun (_) -> io:format("Hello") end, lists:seq(1, 5)).
clojure
(dotimes [_ 5]
(print "Hello"))
(print "Hello"))
fantom
5.times { Env.cur.out.print("Hello") }
for (i := 0; i < 5; i++)
Env.cur.out.print("Hello")
Env.cur.out.print("Hello")
(1..5).each { Env.cur.out.print("Hello") }
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!"
python
print " .. ".join(str(i) for i in range(10, 0, -1)), ".. 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").
clojure
(dotimes [i 10]
(print (str (- 10 i) " .. ")))
(println "Liftoff!")
(print (str (- 10 i) " .. ")))
(println "Liftoff!")
fantom
(10..1).each { Env.cur.out.print("$it .. ") }
Env.cur.out.print("Liftoff!")
Env.cur.out.print("Liftoff!")
for (i := 10; i >= 1; i--)
Env.cur.out.print("$i .. ")
Env.cur.out.print("Liftoff!")
Env.cur.out.print("$i .. ")
Env.cur.out.print("Liftoff!")
