------------------------------- Range e prodotto cartesiano insiemi scala> (1 to 3) res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3) scala> (1 to 3).map(x=>(1 to 3)) res1: scala.collection.immutable.IndexedSeq[scala.collection.immutable.Range.Inclusive] = Vector(Range(1, 2, 3), Range(1, 2, 3), Range(1, 2, 3)) scala> (1 to 3).map(x=>(1 to 3).map(y=>(x,y))) res2: scala.collection.immutable.IndexedSeq[scala.collection.immutable.IndexedSeq[(Int, Int)]] = Vector(Vector((1,1), (1,2), (1,3)), Vector((2,1), (2,2), (2,3)), Vector((3,1), (3,2), (3,3))) scala> (1 to 3).map(x=>(1 to 3).map(y=>(x,y))).flatten res3: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3)) ------------------------------- Prodotto cartesiano di insiemi con for comprehension scala> for (x <- 1 to 3; y <- 1 to 3) yield (x,y) res4: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3)) ------------------------------- Esempio for comprehension object Test extends App { val l = for { i <- 1 to 3 // generatore val test = i%2==0 // dichiarazione if (test) // filtro j <- i to 3 // generatore } yield (2*i,2*j) println(l) } ------------------------------- Currificazione di funzioni scala> val f = (x:Int, y:Int) => x+y f: (Int, Int) => Int = scala> f(10,5) res0: Int = 15 scala> val g = (x:Int) => (y:Int) => x+y g: Int => (Int => Int) = scala> g(10)(5) res1: Int = 15 scala> val somma10 = g(10) somma10: Int => Int = scala> somma10(5) res2: Int = 15 ------------------------------- Algoritmo quicksort: scala> def qsort(l:List[Int]):List[Int] = { | if (l.size < 2) l | else { | val (a,b) = l.tail.partition(_ qsort(List(6,2,7,4,5,3,6,9)) res3: List[Int] = List(2, 3, 4, 5, 6, 6, 7, 9) ------------------------------- Metodi parzialmente applicati: scala> def f(x:Int)(y:Int) = x+y f: (x: Int)(y: Int)Int scala> f(10) :12: error: missing arguments for method f; follow this method with `_' if you want to treat it as a partially applied function f(10) ^ scala> f(10) _ res5: Int => Int = scala> val somma10:Int=>Int = f(10) somma10: Int => Int = scala> somma10(5) res6: Int = 15 ------------------------------- Algoritmo quicksort come metodo parzialmente applicato: object QSort extends App { def qsort(cmp:(Int,Int)=>Int)(l:List[Int]):List[Int] = if (l.size < 2) l else { val (a,b) = l.tail.partition(x=>cmp(x,l.head)<0) qsort(cmp)(a) ::: (l.head :: qsort(cmp)(b)) } val ordinaDecr = qsort((x,y) => if (xy) -1 else 0) _ val s = ordinaDecr(List(3,5,1,7,9,3,2)) println(s) } ------------------------------- Funzioni generiche: scala> def toStringList[T](l:List[T]):List[String] = l.map(x => x.toString) creaLista: [T](l: List[T])List[String] scala> toStringList(List(1,3,2)) res0: List[String] = List(1, 3, 2) scala> toStringList(List(1.3,3.1,2.7)) res1: List[String] = List(1.3, 3.1, 2.7) scala> toStringList(List(1.3,3.1,2.7)).reduce(_+_) res2: String = 1.33.12.7