有時候,一個函式接受很多引數時,很難記住它們該以什麼順序傳入。為了提升可讀性,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("🍔🍔🍔", "🍔", "🍕")
你是一間高級餐廳的經理,餐廳裡還有一座規模不小的酒窖。你的顧客中有很多是講究的葡萄酒愛好者。要為某位顧客找到對的那瓶酒,可不是件容易的事。
身為一位懂技術的餐廳老闆,你決定寫個應用程式來加快選酒的流程,讓客人可以依照自己的喜好篩選你的酒款。
一瓶葡萄酒以自訂型別表示,而所有的酒款則存放在陣列中。
[
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),
// ]