如何替换通用匿名函数?

How to substitute generic anonymous functions?

假设有腿动物有一个特征:

trait Legged {
  val legs: Int

  def updateLegs(legs: Int): Legged
}

还有两只这样的有腿动物:

case class Chicken(feathers: Int, legs: Int = 2) extends Legged {
  override def updateLegs(legs: Int): Legged = copy(legs = legs)
}

case class Dog(name: String, legs: Int = 4) extends Legged {
  override def updateLegs(legs: Int): Legged = copy(legs = legs)
}

在农场里也有这些动物的饲养员

case class Farm(chicken: Chicken, dog: Dog)

还有一种通过给所有有腿动物增加一条额外的腿来变异所有有腿动物的通用方法

def mutate(legged: Legged): Legged = legged.updateLegs(legged.legs + 1)

问题是如何在Farm上实现一个方法,使其以mutate: Legged => Legged函数为参数,应用到所有Legged动物?

val farm = Farm(Chicken(1500), Dog("Max"))
farm.mapAll(mutate) //this should return a farm whose animals have an extra leg

到目前为止我已经完成了,但实际上并没有用

trait LeggedFunc[T <: Legged] extends (T => T)


case class Farm(chicken: Chicken, dog: Dog) {
  def mapAll(leggedFunc: LeggedFunc[Legged]): Farm = {
    //todo how to implement?
    val c = leggedFunc[Chicken](chicken)
  }
}

我知道如何通过模式匹配来做到这一点,但这会导致潜在的 MatchError

这可以使用方法asInstanceOf

来完成
trait Legged {
  val legs: Int

  def updateLegs(legs: Int): Legged
}

case class Chicken(feathers: Int, legs: Int = 2) extends Legged {
  override def updateLegs(legs: Int): Legged = copy(legs = legs)
}

case class Dog(name: String, legs: Int = 4) extends Legged {
  override def updateLegs(legs: Int): Legged = copy(legs = legs)
}

case class Farm(chicken: Chicken, dog: Dog){
  
  def mapAll(leggedFunc: (Legged) => Legged): Farm = {
   
      copy(
           leggedFunc(chicken.asInstanceOf[Legged]).asInstanceOf[Chicken], 
           leggedFunc(dog.asInstanceOf[Legged]).asInstanceOf[Dog]
          )

   } 
}

def mutate(legged: Legged): Legged = legged.updateLegs(legged.legs + 1)

val farm = Farm(Chicken(1500), Dog("Max"))


println (farm.mapAll(mutate)) // prints: Farm(Chicken(1500,3),Dog(Max,5))

scastie 上试用。

更新:这是一个与您自己的代码更相似的替代实现:

trait LeggedFunc[T <: Legged] extends (T => T)


case class Farm(chicken: Chicken, dog: Dog) {
  def mapAll(leggedFunc: LeggedFunc[ Legged]): Farm = {
    val c = leggedFunc(chicken).asInstanceOf[Chicken]
    val d = leggedFunc(dog).asInstanceOf[Dog]
    copy (c, d)
  }
}

scastie 上试用。

我认为您可以通过使用真正通用的 mutate 方法(带有类型参数)来避免遇到的大多数问题:

def mutate[T <: Legged](legged: T): T = legged.updateLegs(legged.legs + 1)

然后,当应用到 Chicken 时,它将 return 返回 Chicken,同样适用于 Dog

一种可能的方法(类型安全,不使用 asInstanceOf)可以使用对象相关类型。

首先,我们应该添加一个使用具体类型Legged subclasses:

的抽象成员
sealed trait Legged { self =>
  type Me >: self.type <: Legged // F-Bounded like type, Me have to be the same type of the subclasses
  val legs: Int
  def updateLegs(legs: Int): Me
}

然后,Legged subclasses 变成:


case class Chicken(feathers: Int, legs: Int = 2) extends Legged {
  type Me = Chicken
  override def updateLegs(legs: Int): Chicken = copy(legs = legs)
}

case class Dog(name: String, legs: Int = 4) extends Legged {
  type Me = Dog
  override def updateLegs(legs: Int): Dog = copy(legs = legs)
}

通过这种方式,可以定义一个函数,returns Legged 的具体 subclass 通过(类似于@Gaël J 所做的):

trait LeggedFunc {
  def apply(a : Legged): a.Me
}

val mutate = new LeggedFunc { override def apply(legged: Legged): legged.Me = legged.updateLegs(legged.legs + 1) }

最后,Farmclass直接定义为:

case class Farm(chicken: Chicken, dog: Dog) {
  def mapAll(leggedFunc: LeggedFunc): Farm = {
    val c : Chicken = leggedFunc(chicken)
    val d : Dog = leggedFunc(dog)
    Farm(c, d)
  }
}

Scastie 对于 Scala 2

但是为什么要依赖对象类型呢? 在 Scala 3.0 中,可以将 dependent function type 定义为:

type LeggedFunc = (l: Legged) => l.Me
val mutate: LeggedFunc = (l) => l.updateLegs(l.legs + 1)

使此解决方案(对象相关类型)更清晰且类型安全。

Scastie 对于 Scala 3 版本

我将添加到 @gianlucaaguzzi 的回答中,在 Scala 2 dependent/polymorphic 中函数可以用 Shapeless

模拟
import shapeless.ops.hlist.Mapper
import shapeless.{Generic, HList, Poly1}

case class Farm(chicken: Chicken, dog: Dog) {
  def mapAll[L <: HList](mutate: Poly1)(implicit
    generic: Generic.Aux[Farm, L],
    mapper: Mapper.Aux[mutate.type, L, L]
  ): Farm = generic.from(mapper(generic.to(this)))
}

object mutate extends Poly1 {
  implicit def cse[T <: Legged]: Case.Aux[T, T#Me] = 
    at(legged => legged.updateLegs(legged.legs + 1))
}

val farm = Farm(Chicken(1500), Dog("Max"))
println(farm.mapAll(mutate)) // Farm(Chicken(1500,3),Dog(Max,5))