Conditional structures: Difference between revisions

Add example for Grain
(Add example for Grain)
Line 3,068:
}
fmt.Println("I'm off!")</syntaxhighlight>
 
=={{header|Grain}}==
===If statements===
In Grain, if statements are expressions, meaning they can be used for variable assignments.
If they are used as an expression, the return value must be of the same type, meaning an else clause is always required.
If an if statement has nothing returned as the body (the body is of the Void type), the else clause can be omitted.
<syntaxhighlight lang="grain">
let x = if (1 < 2) {
":)"
} else { // The else clause is required here as x is a string
":("
}
 
if (2 > 3) {
print("This should never execute.")
} // We can omit the else clause here
 
// We use else if for chaining
if (1 > 2) {
print("1 is less than 2")
} else if (2 == 3) {
print("2 is 3")
} else {
print("This should always execute.")
}
</syntaxhighlight>
 
===Pattern matching===
Pattern matching in Grain is like a switch-statement with superpowers. Each case of a match defines the pattern that the data could fall into.
<syntaxhighlight lang="grain">
// A match statement more like the traditional switch statement
// often seen in other languages.
enum PizzaTopping { Cheese, Pepperoni, Peppers, Pineapple }
 
let topping = Peppers
 
match (topping) {
Cheese => print("Would it really be pizza without it?"),
Pepperoni => print("An instant classic."),
Peppers => {
// We can use a block for more expressions.
print("For those who like to spice things up.")
},
Pineapple => print("You do you.")
}
</syntaxhighlight>
As well as a traditional switch statement, we can match on the shape of the data.
If we keep with the pizza theme, this looks a bit like this.
<syntaxhighlight lang="grain">
enum Topping { Cheese, Pepperoni, Peppers, Pineapple }
enum Menu { Pizza(Topping), Calzone(Topping) }
 
let item = Calzone(Peppers)
 
match (item) {
Calzone(topping) => {
if (checkSpecials(topping)) {
print("These are half off this week.")
} else {
print("No current specials.")
}
},
_ => print("No current specials.")
}
</syntaxhighlight>
 
=={{header|Harbour}}==