7.29.2008

Finished Exercise #1 for Scala

I've just finished exercise #1 from: knowing.net. Please feel free to critique this code, I am serious about learning Scala and getting introduced to members of the community.

Calculator.scala

package activeactive
class Calculator {
  def main(args:Array[String]): Double = eval(args.toList)
    def eval(args:List[String]): Double = args match {
      case null =>
        throw new IllegalArgumentException(
          "args cannot be null-valued")
      case Nil =>
        throw new IllegalArgumentException(
          "You must provide a function name as the first argument")
      case "sum" :: rest => sum(convertList(rest))
      case "prod" :: rest => product(convertList(rest))
      case "mean" :: rest => mean(convertList(rest))
      case "sqrt" :: rest => sqrt(convertList(rest))
      case _ => throw new IllegalArgumentException(
        "invalid function name. Use 'sum', 'prod', 'mean', or 'sqrt'.")
    }
    def convertList(list: List[String]): List[Double] = list match {
      case Nil => Nil
      case x :: subList => x.toDouble :: convertList(subList)
    }
    def sum(list: List[Double]) =
      (0D :: list) reduceLeft ((x, y) => x+y)
    def product(list: List[Double]) =
      (1D :: list) reduceLeft ((x, y) => x*y)
    def mean(list: List[Double]) = list match {
      case Nil => throw new IllegalArgumentException(
        "The mean function requires at least one operand")
      case _ => sum(list) / list.size
    }
    def sqrt(list: List[Double]) =
      if (sum(list) <= 0)
        throw new IllegalArgumentException(
          "the input values '" + list.toString +
            "' resulted in a sum <= zero.")
      else if (sum(list) == 1D) 1D
      else Math.sqrt(sum(list))
}
EDIT: updated knowing.net link.

1 comment:

Jalex said...

Good job! I like the link to knowing.net - useful. I'll try them out. Lisp isn't dead yet, is it?