酒窖

酒窖

学习练习

简介

带标签的实参

有时一个函数接收很多实参,很难记住它们的先后顺序。为了提高可读性,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),
// ]

2. 获取产自指定国家的所有葡萄酒

实现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)
// ]

3. 获取指定国家中指定颜色的所有葡萄酒

实现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),
// ]
通过 GitHub 编辑 链接将在新窗口或新标签页中打开
Gleam Exercism

准备好开始 酒窖 了吗?

注册 Exercism,借助 33 个概念122 个练习 和真人导师指导,学习并掌握 Gleam,全部免费。