newbie newbie - 25 days ago 25
Scala Question

Scala: How to structure code with intermediate results?

I am trying to implement a function that calculates the area of a triangle in the Euclidean space, using the Heron's formula. Unfortunately I have no idea how to outsource partial functions and then pass them as parameters.

That is what I have so far:

import scala.math._
def sqr(a:Double) = a*a
def length(x1:Double,y1:Double,x2:Double,y2:Double)=sqrt(sqr(x2-x1)+sqr(y2-y1))
val a = length(x1,y1,x2,y2)
val b = length(x2,y2,x3,y3)
val c = length(x3,y3,x1,y1)
val u = 0.5*a*b*c

heron(x1:Double,y1:Double,x2:Double,y2:Double,x3:Double,y3:Double) = sqrt(u*(u-a)*(u-b)*(u-c))


That obviously doesn't work, but I hope you get what I am trying to do.

Answer

I think you just want to define those intermediate values inside of your function:

// btw, using scala.math.power you can write 'power(a, 2)'
def sqr(a: Double): Double = a * a

def length(
  x1: Double, y1: Double,
  x2: Double, y2: Double
): Double = sqrt(
  sqr(x2 - x1) +
  sqr(y2 - y1)
)

def heron(
  x1: Double, y1: Double,
  x2: Double, y2: Double,
  x3: Double, y3: Double
): Double = {

  val a = length(x1, y1, x2, y2)
  val b = length(x2, y2, x3, y3)
  val c = length(x3, y3, x1, y1)
  val u = 0.5 * a * b * c

  sqrt(u * (u - a) * (u - b) * (u - c))
}

I would also recommend you to make more spaces in the code, it makes it more readable.

Comments