関数が多くの引数を取ると、どんな順番で渡せばよいかを覚えるのが難しいことがあります。読みやすさのために、Gleamでは引数に名前を付けてラベルを付けられます。
引数にラベルを付けるには、引数名の前にスペースで区切ってラベル名を指定します。
pub fn replace(
in string: String,
each target: String,
with replacement: String
) -> String {
// ...
}
ラベル付き引数を持つ関数を呼び出すときは、引数をどの順番で渡してもかまいません。次のreplaceの呼び出しは、どれも同じ意味になります。
replace(in: "🍔🍔🍔", each: "🍔", with: "🍕")
replace(each: "🍔", in: "🍔🍔🍔", with: "🍕")
replace(with: "🍕", each: "🍔", in: "🍔🍔🍔")
ラベルはいつでも省略できます。関数にラベル付きの引数があっても、ラベルなしで呼び出すことができます。
replace("🍔🍔🍔", "🍔", "🍕")
かなり大きなワインセラーを備えた高級レストランのマネージャーです。お客様の中には、ワインに強いこだわりを持つ愛好家もたくさんいます。あるお客様にぴったりのワインを1本見つけるのは、決して簡単なことではありません。
テクノロジーに強いレストランのオーナーであるあなたは、ワイン選びのスピードを上げることにしました。お客様が好みに合わせてワインを絞り込めるアプリを作るのです。
ワインのボトルはカスタム型で表現され、ワインは配列に格納されます。
[
Wine("Chardonnay", 2015, "Italy", White),
Wine("Pinot grigio", 2017, "Germany", White),
Wine("Pinot noir", 2016, "France", Red),
Wine("Dornfelder", 2018, "Germany", Rose)
]
wines_of_color関数を実装しましょう。ワインの配列を受け取り、指定した色のワインをすべて返すようにします。
wines_of_color(
[
Wine("Chardonnay", 2015, "Italy", White),
Wine("Pinot grigio", 2017, "Germany", White),
Wine("Pinot noir", 2016, "France", Red),
Wine("Dornfelder", 2018, "Germany", Rose)
],
color: White
)
// -> [
// Wine("Chardonnay", 2015, "Italy", White),
// Wine("Pinot grigio", 2017, "Germany", White),
// ]
wines_from_country関数を実装しましょう。ワインの配列を受け取り、指定した国のワインをすべて返すようにします。
wines_from_country(
[
Wine("Chardonnay", 2015, "Italy", White),
Wine("Pinot grigio", 2017, "Germany", White),
Wine("Pinot noir", 2016, "France", Red),
Wine("Dornfelder", 2018, "Germany", Rose)
],
country: "Germany"
)
// -> [
// Wine("Dornfelder", 2018, "Germany", Rose)
// ]
filter関数を実装しましょう。ワインの配列、色、国を受け取り、指定した色で指定した国で瓶詰めされたワインをすべて返すようにします。
filter(
[
Wine("Chardonnay", 2015, "Italy", White),
Wine("Pinot grigio", 2017, "Germany", White),
Wine("Pinot noir", 2016, "France", Red),
Wine("Dornfelder", 2018, "Germany", Rose)
],
color: White
country: "Italy"
)
// -> [
// Wine("Chardonnay", 2015, "Italy", White),
// ]