加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 09:06:47 所属栏目:安全 来源:网络整理
导读:考虑一个简单的案例类“卡片”,它有两个属性(“数字”和“颜色”),如下所示: case class Card(number: Int,color: String) 考虑像这样的一系列牌: val cards = Seq( Card(5,"red"),Card(7,Card(3,"black")) 现在假设我想用Scala-idiomatic方式解决这些问题
考虑一个简单的案例类“卡片”,它有两个属性(“数字”和“颜色”),如下所示:

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

考虑像这样的一系列牌:

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

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

>查看所有卡片是否具有相同的颜色
>查找所有卡是否具有相同的号码
>查看卡是否按升序排列

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

// 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一旦遇到第一次错误就会短暂退出

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参数的函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读