As part of my learning, I am trying to write the Scala expression into a scala script but struck with an error.
The scala code I am having it successfully executed in Scala REPL is
def intList = List[1,2,3,4,5]
intList.filter(x => x%2 ==1).map(x => x * x).reduce((x,y) => x+y)
This successfully gets executed and the following is the result I get.
scala> intList.filter(x => x % 2 == 1).map(x => x * x).reduce((x,y) => x + y)
res15: Int = 35
I am trying to make this as a Scala script or class so as to rerun any number of times on demand. I save this in a file named SumOfSquaresOfOdd.scala
import scala.collection.immutable.List
object SumOfSquaresOfOdd extends App
{
def main(args:Array[String]):Unit =
{
var intList = List[Integer](1,2,3,4,5,6,7,8,9,10)
def sum = intList.filter(x => x % 2 ==1).map(x => x * x).reduce((x+y) => x + y)
println sum
}
}
When I compile this using scalac, the following error is printed on the console.
λ scalac SumOfSquaresOfOdd.scala
SumOfSquaresOfOdd.scala:8: error: not a legal formal parameter.
Note: Tuples cannot be directly destructured in method or function parameters.
Either create a single parameter accepting the Tuple1,
or consider a pattern matching anonymous function: `{ case (param1, param1) => ... }
def sum = intList.reduce(x => x % 2 ==1).map(x => x * x).reduce((x+y) => x + y)
^
one error found
How do I use the filter, map, reduce methods in a script? Appreciate your help and support.
UPDATE: Typos updated in the code.
I can answer your question:
But I can't fully solve your specific use case because you didn't specify what the script should be doing.
Try this code
Then
You seem to be a little lost. Here are some tips:
Intrather thanInteger;Intis Scala's integer type. And you don't need to import it.Appin this case. Refer to this question Difference between using App trait and main method in scalaprintlnList(1,2,3)will be type-inferenced toList[Int]; no need to explicitly type it. Check in the Scala REPL.reducewithfilter. Compare both in the latest scaladoc: http://www.scala-lang.org/api/current/#scala.collection.immutable.ListGood luck learning Scala! :)