This post originated from an RSS feed registered with Java Buzz
by Ryan Ransford.
Original Post: Finished Exercise #1 for Scala
Feed Title: Active-Active Configuration
Feed URL: http://active-active.blogspot.com/feeds/posts/default
Feed Description: Active-Active Configuration is a blog about making my place in the enterprise world better. This blog is primarily focused on Java articles, but be prepared to be challenged by posts about dynamic languages, agile tools, and the lighter side of geek culture.
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 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)) }