2019/12/23
Scala Hands On!!
1996
WingArc1st MotionBoard
1.
2.
3.
4.
5. Java
6. ( 1 2)
7. ( 1 2 )
1
val add = calc(2,4,(a,b) => a+b)
val sub = calc(2,4,(a,b) => a-b)
val mul = calc(2,4,(a,b) => a*b)
•
def calc(a: Int, b: Int, f: (Int,Int) => Int ):Int = f(a,b)
f:(Int,Int) Int
1
def addFunc(a: Int, b: Int) = a+b
val add = calc(2,4,addFunc)
•
def calc(a: Int, b: Int, f: (Int,Int) => Int ):Int = f(a,b)
f:(Int,Int) Int
1 0 0 1 0 1 0 0 1 1 1
val list = Seq(9,-4,-2,6,-2,5,0,-7,5,3,10)
list.map(e => if(e>0) 1 else 0).foreach(e => print(e+" "))
1 0 map
1
2
val str = Random.nextInt(10) match {
case 0 | 1 => "0 1"
case i if(i%2 == 0) => " "
case i if(i%3 == 0) => "3 "
case _ => " "
}
• |
• case _
2
•
• case Nil
• l: List[Int]
val list = Seq(1,2,3)
val str1 = list match {
case List(1,a,b) => s"1 and a+b=${a+b}"
case List(x,y) => x+y
case Nil => " "
case l: List[Int] => " :"+l.toString()
case _ => " "
}
3
Option[A] Option[A] Some[A] None
Option
val a: String = null
val option: Option[String] = Option(a)
if(option.isDefined){
println(option.get)
}else{
println("Nothing!!")
}
3
option match {
case Some(x) => f(x)
case None => ()
}
option match {
case Some(x) => Some(f(x))
case None => None
}
option match {
case Some(x) if p(x) => Some(x)
case _ => None
}
option.foreach(println)
option.map(_+"¥n")
option.filter(!_.equals(""))
Option
3
Either
def fileSize(file: File): Either[String,Long] = {
if(file.exists) Right(file.length) else Left("Not exists!!")
}
val f = new File("a/b.txt")
val size: Either[String,Long] = fileSize(f)
if(size.isRight){
println("file size :"+size.right.get)
}else{
println("error :"+size.left.get)
}
Either[A,B] Left[A] Right[B]
3
fileSize(f) match {
case Right(size) => println("file size :"+size)
case Left(str) => println("error :"+str)
}
Either
Left Right
3
Try Option/Either
def div(x: Int,y: Int):Try[Int] = Try(x/y)
div(14,0) match {
case Success(value) => println(value)
case Failure(exception) => exception.printStackTrace()
}
Try(x/y) Failure[Trowable]
Success(x/y)
java.lang.ArithmeticException Failure
4
scala.collection.immutable scala.collection.mutable
immutable
4
Seq C A B...C … A
B
A
DC A
key value
B
C
1
3
2Set Map
4
Seq //
val seq = Seq("A","B","C","B","G")
//
val b = seq(1) //
val head = seq.head //
val last = seq.last //
//
val newSeq1 = seq :+ "F" //
val newSeq2 = seq +: "F" //
val newSeq3 = seq ++ Seq("1","2","3")
4
//
val set = Set("A","B","C","B","G")
//
val contains:Boolean = set("C")
//
val newSet1 = set + "F"
val newSet2 = set ++ Set("F","G","5")
Set
4
Map //
val map = Map("Apple" -> 140, "Orange" -> 90)
// key value
val apple = map("Apple")
val lemon = map.get(“Lemon”) // Option
//
val newMap1 = map + ("Banana"->110)
val newMap2 = map ++ Map("Banana"->110,"Lemon"->70)
4
• flatten
•
val words = Iterable(
Seq("H","e","l","l","o"),
Seq(" ","S","c","a","l","a"),
Seq("!","!"))
println(words.flatten)
List(H, e, l, l, o, , S, c, a, l, a, !, !)
Hello!!
val s = Seq("H","e","l","l","o","!","!")
val hello = s.foldLeft("")((accumurator,element) =>
accumurator + element
)
println(hello)
4
5 Java
import java.util.{Date, Locale}
import java.text.DateFormat._
val now = new Date
val df = getDateInstance(LONG,Locale.ENGLISH)
println(df.format(now))
Java
•
• _ Java *
5 Java
val file:Path = Paths.get("file.txt")
val lines:List[String] = Files.readAllLines(file)
lines.asScala.foreach(println)
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.Files
import java.util.List
import scala.collection.JavaConverters._
.asScala .asJava
Java
Scala
6
( )
input: 10 ss 20
mean: 15.0
input: ewqg 3 4 f500 3 5 8 4 5 6 0 w 5
mean: 4.3
1
6
• ( )
val in:Array[String] = StdIn.readLine().split(" ")
val str:String = "14"
val i:Int = str.toInt
• String Int
java.lang.NumberFormatException
•
val list = Iterable(10,44,23,47)
val size: Int = list.size
6
2
6
7
1 2
1
import scala.io.StdIn
import scala.util.Try
import scala.util.Success
import scala.util.Failure
1
def parseInt(str: String): Option[Int] = {
Try(str.toInt) match {
case Success(value) => Some(value)
case Failure(exception) => None
}
}
def inputNums():Iterable[Int]= {
val in:Array[String] = StdIn.readLine().split(" ")
val nums = in
.map(parseInt(_)) // Option
.filter(_.isDefined) // None
.map(_.get) //
nums
}
Int
1
def mean(sample: Iterable[Int]): Double = {
val sum = sample.foldLeft(0)((a,b)=>a+b) //
sum/sample.size.toDouble //
}
print("input: ")
val sample = inputNums()
val res = mean(sample)
println(" mean: "+res)
main
2
import scala.io.Source
import scala.util.Try
import scala.util.Success
import scala.util.Failure
import scala.collection.mutable
2
def getLinesFromfile(path: String):Iterable[String] = {
Try(Source.fromFile(path,"UTF-8")) match {
case Success(value) => value.getLines().toIterable
case Failure(e) => e.printStackTrace();Nil
}
}
I hava a dream.
I have a dream today. I hava a dream. I hava a dream today.
2
1 1
def toWords(lines: Iterable[String]): Iterable[String] = {
val remove = (ward: String,keys: Set[Char]) => ward.filter(!keys(_))
lines.map(_.split(" ")).flatten
.map(remove(_,Set('¥n','.',',','“','”','¥'','’','–')))
}
I hava a dream. I hava a dream today.
I have a dream I have a dream today
2
main
val path = "a/texts/ihaveadream.txt"
//
val wards: Iterable[String] = toWords(getLinesFromfile(path))
//
val set: Set[String] = wards.toSet
//
val keyMap: mutable.Map[String,Int] = mutable.Map.empty ++ set.map(_ -> 0).toMap
//
wards.foreach(keyMap(_)+=1)
//
keyMap.toSeq.sortBy(_._2).foreach(println)
mutable.Map …
Scala Hands On!!

Scala Hands On!!

  • 1.
  • 2.
  • 3.
    1. 2. 3. 4. 5. Java 6. (1 2) 7. ( 1 2 )
  • 4.
    1 val add =calc(2,4,(a,b) => a+b) val sub = calc(2,4,(a,b) => a-b) val mul = calc(2,4,(a,b) => a*b) • def calc(a: Int, b: Int, f: (Int,Int) => Int ):Int = f(a,b) f:(Int,Int) Int
  • 5.
    1 def addFunc(a: Int,b: Int) = a+b val add = calc(2,4,addFunc) • def calc(a: Int, b: Int, f: (Int,Int) => Int ):Int = f(a,b) f:(Int,Int) Int
  • 6.
    1 0 01 0 1 0 0 1 1 1 val list = Seq(9,-4,-2,6,-2,5,0,-7,5,3,10) list.map(e => if(e>0) 1 else 0).foreach(e => print(e+" ")) 1 0 map 1
  • 7.
    2 val str =Random.nextInt(10) match { case 0 | 1 => "0 1" case i if(i%2 == 0) => " " case i if(i%3 == 0) => "3 " case _ => " " } • | • case _
  • 8.
    2 • • case Nil •l: List[Int] val list = Seq(1,2,3) val str1 = list match { case List(1,a,b) => s"1 and a+b=${a+b}" case List(x,y) => x+y case Nil => " " case l: List[Int] => " :"+l.toString() case _ => " " }
  • 9.
    3 Option[A] Option[A] Some[A]None Option val a: String = null val option: Option[String] = Option(a) if(option.isDefined){ println(option.get) }else{ println("Nothing!!") }
  • 10.
    3 option match { caseSome(x) => f(x) case None => () } option match { case Some(x) => Some(f(x)) case None => None } option match { case Some(x) if p(x) => Some(x) case _ => None } option.foreach(println) option.map(_+"¥n") option.filter(!_.equals("")) Option
  • 11.
    3 Either def fileSize(file: File):Either[String,Long] = { if(file.exists) Right(file.length) else Left("Not exists!!") } val f = new File("a/b.txt") val size: Either[String,Long] = fileSize(f) if(size.isRight){ println("file size :"+size.right.get) }else{ println("error :"+size.left.get) } Either[A,B] Left[A] Right[B]
  • 12.
    3 fileSize(f) match { caseRight(size) => println("file size :"+size) case Left(str) => println("error :"+str) } Either Left Right
  • 13.
    3 Try Option/Either def div(x:Int,y: Int):Try[Int] = Try(x/y) div(14,0) match { case Success(value) => println(value) case Failure(exception) => exception.printStackTrace() } Try(x/y) Failure[Trowable] Success(x/y) java.lang.ArithmeticException Failure
  • 14.
  • 15.
    4 Seq C AB...C … A B A DC A key value B C 1 3 2Set Map
  • 16.
    4 Seq // val seq= Seq("A","B","C","B","G") // val b = seq(1) // val head = seq.head // val last = seq.last // // val newSeq1 = seq :+ "F" // val newSeq2 = seq +: "F" // val newSeq3 = seq ++ Seq("1","2","3")
  • 17.
    4 // val set =Set("A","B","C","B","G") // val contains:Boolean = set("C") // val newSet1 = set + "F" val newSet2 = set ++ Set("F","G","5") Set
  • 18.
    4 Map // val map= Map("Apple" -> 140, "Orange" -> 90) // key value val apple = map("Apple") val lemon = map.get(“Lemon”) // Option // val newMap1 = map + ("Banana"->110) val newMap2 = map ++ Map("Banana"->110,"Lemon"->70)
  • 19.
    4 • flatten • val words= Iterable( Seq("H","e","l","l","o"), Seq(" ","S","c","a","l","a"), Seq("!","!")) println(words.flatten) List(H, e, l, l, o, , S, c, a, l, a, !, !) Hello!! val s = Seq("H","e","l","l","o","!","!") val hello = s.foldLeft("")((accumurator,element) => accumurator + element ) println(hello)
  • 20.
  • 21.
    5 Java import java.util.{Date,Locale} import java.text.DateFormat._ val now = new Date val df = getDateInstance(LONG,Locale.ENGLISH) println(df.format(now)) Java • • _ Java *
  • 22.
    5 Java val file:Path= Paths.get("file.txt") val lines:List[String] = Files.readAllLines(file) lines.asScala.foreach(println) import java.nio.file.Path import java.nio.file.Paths import java.nio.file.Files import java.util.List import scala.collection.JavaConverters._ .asScala .asJava Java Scala
  • 23.
    6 ( ) input: 10ss 20 mean: 15.0 input: ewqg 3 4 f500 3 5 8 4 5 6 0 w 5 mean: 4.3 1
  • 24.
    6 • ( ) valin:Array[String] = StdIn.readLine().split(" ") val str:String = "14" val i:Int = str.toInt • String Int java.lang.NumberFormatException • val list = Iterable(10,44,23,47) val size: Int = list.size
  • 25.
  • 26.
  • 27.
  • 28.
    1 import scala.io.StdIn import scala.util.Try importscala.util.Success import scala.util.Failure
  • 29.
    1 def parseInt(str: String):Option[Int] = { Try(str.toInt) match { case Success(value) => Some(value) case Failure(exception) => None } } def inputNums():Iterable[Int]= { val in:Array[String] = StdIn.readLine().split(" ") val nums = in .map(parseInt(_)) // Option .filter(_.isDefined) // None .map(_.get) // nums } Int
  • 30.
    1 def mean(sample: Iterable[Int]):Double = { val sum = sample.foldLeft(0)((a,b)=>a+b) // sum/sample.size.toDouble // } print("input: ") val sample = inputNums() val res = mean(sample) println(" mean: "+res) main
  • 31.
    2 import scala.io.Source import scala.util.Try importscala.util.Success import scala.util.Failure import scala.collection.mutable
  • 32.
    2 def getLinesFromfile(path: String):Iterable[String]= { Try(Source.fromFile(path,"UTF-8")) match { case Success(value) => value.getLines().toIterable case Failure(e) => e.printStackTrace();Nil } } I hava a dream. I have a dream today. I hava a dream. I hava a dream today.
  • 33.
    2 1 1 def toWords(lines:Iterable[String]): Iterable[String] = { val remove = (ward: String,keys: Set[Char]) => ward.filter(!keys(_)) lines.map(_.split(" ")).flatten .map(remove(_,Set('¥n','.',',','“','”','¥'','’','–'))) } I hava a dream. I hava a dream today. I have a dream I have a dream today
  • 34.
    2 main val path ="a/texts/ihaveadream.txt" // val wards: Iterable[String] = toWords(getLinesFromfile(path)) // val set: Set[String] = wards.toSet // val keyMap: mutable.Map[String,Int] = mutable.Map.empty ++ set.map(_ -> 0).toMap // wards.foreach(keyMap(_)+=1) // keyMap.toSeq.sortBy(_._2).foreach(println) mutable.Map …