折叠上有什么好的教程?
原始问题,从删除中恢复以提供其他答案的上下文:
我正在尝试实现一种方法来查找矩形,圆形,位置和所有扩展形状的组的boudning框.组基本上是一组形状
abstract class Shape
case class Rectangle(width: Int, height: Int) extends Shape
case class Location(x: Int, y: Int, shape: Shape) extends Shape
case class Circle(radius: Int) extends Shape
case class Group(shape: Shape*) extends Shape
Run Code Online (Sandbox Code Playgroud)
我得到了除第一组之外的所有三个计算的边界框.所以现在对于边界框方法我知道我应该使用map并向左折叠为Group,但我无法找到创建它的确切语法.
object BoundingBox {
def boundingBox(s: Shape): Location = s match {
case Circle(c)=>
new Location(-c,-c,s)
case Rectangle(_, _) =>
new Location(0, 0, s)
case Location(x, y, shape) => {
val b = boundingBox(shape)
Location(x + b.x, y + b.y, b.shape)
}
case Group(shapes …Run Code Online (Sandbox Code Playgroud) 跟进这个问题,我不知道为什么 maxBy的Traversable[T]返回一个值T,而不是一个序列T(列表或类似).这看起来很常见.例如(来自上一个问题):
有关成绩的学生名单
List(Student("Mike", "A"), Student("Pete", "B"), Student("Paul", A))"
我想得到
List(Student("Mike", "A"), Student("Paul", A))
有没有人知道任何标准实现maxBy,它返回一系列找到的项目?