gpt4 book ai didi

scala - 检查案例类实例集合的属性

转载 作者:行者123 更新时间:2023-12-01 09:57:36 24 4
gpt4 key购买 nike

考虑一个简单的案例类“卡片”,它具有两个属性(“数字”和“颜色”),如下所示:

case class Card(number: Int, color: String)

考虑像这样的一系列卡片:

val cards = Seq(
Card(5, "red"),
Card(7, "red"),
Card(3, "black"))

现在假设我想以 Scala 惯用的方式(以功能为导向?)解决这些问题:

  • 判断所有卡片的颜色是否相同
  • 判断所有卡片的号码是否相同
  • 判断卡片是否按升序排列

具体来说,我必须实现这些功能:

// Do the cards all have the same color?
def haveSameColor(cards: Seq[Card], ifEmpty: Boolean = true): Boolean = {
???
}

// Do the cards all have the same number?
def haveSameNumber(cards: Seq[Card], ifEmpty: Boolean = true): Boolean = {
???
}

// Are cards ordered ascendingly?
def areAscending(cards: Seq[Card], ifEmpty: Boolean = true): Boolean = {
???
}

什么是可能的/最好的方法?循环、递归、折叠、减少?

最佳答案

forall 一旦遇到第一个 false 就立即退出

def haveSameColor(cards: Seq[Card], ifEmpty: Boolean = true) = {
if (cards.isEmpty) ifEmpty
else cards.forall(x => x.color.equals(cards.head.color))
}

// not much different approach
def haveSameNumber(cards: Seq[Card], ifEmpty: Boolean = true): Boolean = {
if (cards.isEmpty) ifEmpty
else cards.forall(x => x.number == cards.head.number)
}

def areAscending(cards: Seq[Card], ifEmpty: Boolean = true): Boolean = {
if (cards.isEmpty) ifEmpty
else cards.zip(cards.tail).forall{ case (prev, next) => prev.number <= next.number}
}

虽然,你说

is it clear what the default answer should be in case of emptiness? It is not for me.

如您所见,函数中有很多重复——这是错误的明显标志——我会选择不带 ifEmpty 参数的函数。

关于scala - 检查案例类实例集合的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22606081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com