In [1]:
def runLength[A](l: List[A]): List[(A, Int)] = l.foldLeft(List.empty[(A, Int)]){
case ((x, n) :: xs, a) if x == a => {
println("(x : " + x + ", n+1 : " + n+1 + ") :: xs : " + xs)
(x, n+1) :: xs
}
case (acc, a) => {
println("(a : " + a + ", 1) :: acc : " + acc)
(a,1) :: acc
}
}.reverse
println("abbbcc".toList)
println(runLength("abbbcc".toList))
Out[1]:
In [2]:
def runLength[A](l: List[A]): List[(A, Int)] = l.foldLeft(List.empty[(A, Int)]){
case ((x, n) :: xs, a) if x == a =>
println(s"${(x,n)::xs}* , $a")
(x, n + 1) :: xs
case (acc, a) =>
println(s"$acc, $a")
(a, 1) :: acc
}.reverse
println(runLength("abbbcc".toList))
println("Ok!")
Out[2]:
In [ ]:
def fizzBuzz(n: Int)(cond: (Int, String)*): Unit = ???
In [5]:
def fizzBuzz(n: Int)(cond: (Int, String)*): Unit = 1 to n map { i =>
cond.foldLeft(""){ case (acc, (x, s)) => if (i % x == 0) acc + s else acc } match {
case "" => i.toString
case other => other
}
} foreach println
fizzBuzz(20)((3, "Fizz"), (5, "Buzz"))
println("OK")
Out[5]:
In [6]:
Seq(1, 2, 3).map(_ * 2)
Out[6]:
In [7]:
// For Comprehensions 표현
for {
x <- Seq(1, 2, 3)
} yield x * 2
Out[7]:
In [8]:
val data = Seq(Seq(1), Seq(2, 3), Seq(4, 5, 6))
Out[8]:
In [9]:
data.flatMap(_.map(_ * 2))
Out[9]:
In [11]:
// For Comprehensions 표현
for {
subseq <- data
element <- subseq
} yield element * 2
Out[11]:
In [15]:
a.flatMap(x => b.flatMap(y => c.map(z => e)))
In [ ]:
for(x <-a ; y <- b; z <- c) yield e
In [12]:
for { x <- Seq(-2, -1, 0, 1, 2) if x > 0 } yield x
Out[12]:
In [13]:
Seq(1, 2, 3) zip Seq(4, 5, 6)
Out[13]:
In [14]:
for{
(x, y) <- Seq(1, 2, 3) zip Seq(4, 5, 6)
} yield x + y
Out[14]:
In [15]:
for(x <- Seq(1, 2, 3).zipWithIndex) yield x
Out[15]:
In [16]:
for {
x <- Seq(1, 2, 3)
square = x * x
y <- Seq(4, 5, 6)
} yield square * y
Out[16]:
In [17]:
def readInt(str: String): Option[Int] = if (str matches "\\d+") Some(str.toInt) else None
Out[17]:
In [18]:
readInt("!@#")
Out[18]:
In [19]:
readInt("123")
Out[19]:
In [20]:
readInt("a")
Out[20]:
In [21]:
readInt("1")
Out[21]:
In [22]:
// 값을 꺼내고 싶을 경우
readInt("abc").getOrElse(0)
// 값이 없다면 default 0 값
Out[22]:
In [23]:
readInt("123") match {
case Some(number) => number + 1
case None => 0
}
Out[23]:
In [ ]:
sealed abstract class Option[+A] extends Product with Serializable {
def getOrElse(default: A): A
def isEmpty: Boolean
def isDefined: Boolean = !isEmpty
def filter(func: A => Boolean): Option[A]
def find(func: A => Boolean): Option[A]
def map[B](func: A => B): Option[B]
def flatMap(func: A => Option[B]): Option[B]
def foreach(func: A => Unit): Unit
def foldLeft[B](initial: B)(func: (B, A) => B): B
def foldRight[B](initial: B)(func: (A, B) => B): B
}
In [24]:
def sum(optionA: Option[Int], optionB: Option[Int]): Option[Int] =
optionA.flatMap(a => optionB.map(b=> a + b))
sum(readInt("1"), readInt("2"))
sum(readInt("1"), readInt("b"))
sum(readInt("a"), readInt("2"))
Out[24]:
In [25]:
def sum(optionA: Option[Int], optionB: Option[Int]): Option[Int] = for {
a <- optionA
b <- optionB
} yield a + b
Out[25]:
In [26]:
//proper way to wrap calls to java apis
val map = new java.util.HashMap[String, String]()
map.put("key1", "value1")
val maybeValue1 = Option(map.get("key1")) //Some("value1")
val maybeValue2 = Option(map.get("key2")) //None
Out[26]:
In [27]:
def readInt(str: String): Option[Int] = Option(str.toInt)
Out[27]:
In [28]:
println(readInt("123"))
In [30]:
val ans0 = readInt("123") match {
case Some(number) => number + 1
case None => 0
}
Out[30]:
In [31]:
val ans1 = readInt("123").fold(0)(_ + 1)
// 없으면 0 아니면 +1
Out[31]:
In [ ]:
def calculator(operand1: String, operator: String, operand2: String): String
In [ ]:
// 헬퍼 method를 2개 만듬
// string to int
// eval
In [32]:
def calculator(operand1: String, operator: String, operand2: String): String = {
def readInt(str: String): Option[Int] = if (str matches "\\d+") Some(str.toInt) else None
def eval(a: Int, op: String, b: Int): Option[Int] = op match {
case "+" => Some(a + b)
case "-" => Some(a - b)
case "*" => Some(a * b)
case "/" => if (b == 0) None else Some(a / b)
case _ => None
}
val ansOp = for(a<-readInt(operand1); b<-readInt(operand2); ans<-eval(a, operator, b)) yield ans
ansOp.fold(s"Error calculating $operand1 $operator $operand2")(ans => s"The answer is $ans!")
}
assert(calculator("1", "+", "1") == "The answer is 2!")
assert(calculator("1", "/", "0") == "Error calculating 1 / 0")
println("Ok!")
Out[32]:
In [33]:
val right1 = Right(1) : Right[Double, Int]
val right2 = Right(2)
val right3 = Right(3)
val left23 = Left(23.0) : Left[Double, Int]
val left42 = Left(42.0)
Out[33]:
In [33]:
for {
x <- right1
y <- right2
z <- right3
} yield x + y + z // Right(6)
In [33]:
for {
x <- right1
y <- right2
z <- left23
} yield x + y + z // Left(23.0)
In [33]:
for {
x <- right1
y <- left23
z <- right2
} yield x + y + z // Left(23.0)
In [34]:
val example = Map("a" -> 1, "b" -> 2, "c" -> 3)
Out[34]:
In [35]:
"a" -> 1
Out[35]:
In [36]:
example("a")
Out[36]:
In [37]:
example.get("a")
Out[37]:
In [38]:
example("d")
In [39]:
example.get("d")
Out[39]:
In [40]:
example.getOrElse("d", -1)
Out[40]:
In [41]:
example.contains("a")
Out[41]:
In [42]:
example.size
Out[42]:
In [43]:
example.+("c" -> 10, "d" -> 11, "e" -> 12)
Out[43]:
In [44]:
example.-("b", "c")
Out[44]:
In [45]:
example + ("d" -> 4) - "c"
Out[45]:
In [50]:
val map = Map("a"->1) + ("b"->2) + ("c"->3) + ("d"->4) + ("e"->5)
Out[50]:
In [51]:
map.toSeq
Out[51]:
In [ ]:
In [48]:
// sort된 것이 보고싶다면
scala.collection.SortedMap("a"->1) + ("b"->2) + ("c"->3) + ("d"->4) + ("e"->5)
Out[48]:
In [55]:
// scala 생략 가능
val map = collection.SortedMap("a"->1) + ("b"->2) + ("c"->3) + ("d"->4) + ("e"->5)
Out[55]:
In [56]:
map.toSeq
Out[56]:
In [57]:
for {(k, v) <- map } yield s"($k->$v)"
Out[57]:
In [60]:
val set = Set(1, 1, 2, 2, 3, 3)
Out[60]:
In [64]:
// 정렬하고 싶다면
val set1 = scala.collection.SortedSet(1,2,3,4,5,6,7)
Out[64]:
In [61]:
set.toSeq
Out[61]:
In [65]:
set1.toSeq
Out[65]:
In [63]:
for { x <- set } yield x * 2
// set을 연산해도 set
Out[63]:
In [66]:
for { x <- set1 } yield x * 2
Out[66]:
In [ ]: