Euler problems in Scala

SRT is abuzz with solving the Euler problems, in our collective spare time, and in different languages.

Bill Wagner has been solving the problems on euler.net in C#/LINQ.  Darrell Hawley is attacking them in Python.  Marina Fedner is giving us a flavor for Ruby.  And so I'll jump in, in Scala.   And no, we're not looking at each other's solutions before doing our own! 

Here's my Scala solution to problem 1, which is to sum the numbers between 0 and 1000 that are divisible by either 3 or 5.

    val nums = 3 until 1000
   
    val somenums = nums.filter(x => (x % 3 == 0 || x % 5 ==0))
   
    var sum = 0

    somenums.foreach(sum += _)
    println (sum)

I figured that there was no sense starting with a number less than 3 (not that it made much difference to the solution, but what the heck).  The filter function (on lists) in Scala provides a nice way to grab the appropriate values.  The foreach expression, when combined with the "_", which is a placeholder for the parameter. 

 Alternately, I could have defined a temporary variable x, like this:

for (x <- somenums)   sum += x
 

So, does the temporary variable "x" improve readability?  Perhaps somewhat, until you get used to the new syntax.  There are certainly times in Scala where I appreciate the more verbose syntax (and am grateful for its legality), but in this case, I prefer the more concise "foreach".

Sidenote: as Bill mentioned in his solution, the goal here is not necessarily to provide the most optimal, functional solution.  It's to provide one that works, and learn/expose information about how to use the language along the way.  And people who are interested in solving the problems themselves should probably avoid our posts on this subject.

Published 08 April 2008 01:39 PM by dmarsh
Filed under: ,

Comments

# James Iry said on 12 April, 2008 01:03 AM

That solution is fine, but its worth while to look into the fold/reduce family of functions (available in many functional languages).  Here's what it looks like in Scala.

val nums = 3 until 1000

val somenums = nums filter (x => (x % 3 == 0 || x % 5 ==0))

val sum = somenums reduceLeft {(x:Int,y:Int) => x + y}

println(sum)

# dmarsh said on 19 April, 2008 08:21 AM

That's a great modification!  Learning Scala is definitely more than just learning the syntax.  Learning how to effectively use the functional constructs is really key to getting to the next level.  Thanks!  

# Joel Neely said on 26 April, 2008 04:00 PM

It's good to see that James Iry found you and beat me to the punch on folds. They're quite addictive!

I'll be keeping an eye out for your new solutions.

# Languages and Community said on 29 April, 2008 04:43 PM

James Iry pointed out that I could have used a fold left in my solution to the first ProjectEuler problem