
Unlike Scala where you would have the function sliding on string objects, we need to call chars on the string to get an array of the characters. What happens next is that I map the function to_i(nteger) on the resulting array to get an array of integers. And then each_cons enters! (The argument here is obviously the window size.) I then map the resulting enumerator (I could also have sent it to a block) to a simple anonymous function that multiplies all the elements together before returning the max value of this new array.
Voila, we have the largest product of five consecutive numbers within a 1000 digit number. Functional and concise. (I won't give you the number of the Euler problem, as that would probably break some (un)written rule...)
BTW: The article mentioned above is on the expressiveness of Java vs Scala and starts off on a reflection from the author on how he took a project from 2500 lines of Java code to 250 lines of Scala code after having programmed in Scala only 6 months.
Comments
Post a Comment