Writing lazy curried in scala with multiple parameters

152 views Asked by At

I'm writing code for a game as an exercise to learn Scala after getting acquainted with Haskell. I started with an ADT as follows:

sealed class Circle(x: Double, y: Double, r: Double)

case class PlayerCircle (x: Double, y: Double, r: Double) extends Circle(x, y, r)

case class AICircle (x: Double, y: Double, r: Double) extends Circle(x, y, r)

I'm trying to write a lazy, curried val that does as follows (in Haskell pseudocode):

addToPlayer :: PlayerCircle -> Circle -> PlayerCircle
addToPlayer (PlayerCircle px py pr) (AICircle _ _ cr) = PlayerCircle px py (pr + cr)
addToPlayer player _ = player

I have the following:

def addToPlayer (wcircle : Circle) : PlayerCircle = wcircle match {
    case AICircle (_, _, wr) => copy(this.x, this.y, this.r + wr)
    case _ => this
}

What is necessary to make this function curried and lazy?

Edit: I've googled for the answer but haven't found any article of use so please help me with this one.

2

There are 2 answers

0
bjfletcher On

Here's a curried function example:

def addToPlayer(c: Circle, p: Player) = ... actual code...
def addToPlayer(c: Circle) = p: Player => addToPlayer(c, p)

Then you can do this:

val partial = addToPlayer(c)
val complete = partial(p)

This is lazy because addToPlayer(c, p) isn't run until both parameters are given.

HTH.

0
harshtuna On

maybe this way

def addToPlayer(p: PlayerCircle)(c: Circle): PlayerCircle = c match {
  case AICircle(_, _, wr) => p.copy(p.x, p.y, p.r + wr)
  case _ => p
}