Last active
November 19, 2016 13:48
-
-
Save MasseGuillaume/cf2df37d4144130d1550de8ab5c4ef5f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// rec and pat mat | |
last(List(1, 2, 3)) == 3 | |
def last(xs: List[Int]): Int = { | |
xs match { | |
case h :: Nil => h // List(1) | |
case h :: t => last(t) // List(1, ...) | |
case Nil => throw new NoSuchElementException | |
} | |
} | |
/* === */ | |
last(List(1, 2, 3)) == 3 | |
last(List("a", "b")) | |
// rec and pat mat | |
def last[T](xs: List[T]): T = { | |
xs match { | |
case h :: Nil => h // List(1) | |
case h :: t => last(t) // List(1, ...) | |
case Nil => throw new NoSuchElementException | |
} | |
} | |
/* === */ | |
last(List(1, 2, 3)) | |
last(List("a", "b")) | |
last(List()) | |
// rec and pat mat | |
def last[T](xs: List[T]): Option[T] = { | |
xs match { | |
case h :: Nil => Some(h) // List(1) | |
case h :: t => last(t) // List(1, ...) | |
case Nil => Option.empty[T] | |
} | |
} | |
val xs = List(1, 2, 3) | |
xs(3) | |
implicit class ListExtention[T](xs: List[T]) { | |
def get(n: Int): Option[T] = | |
if(n >= xs.size) None | |
else Some(xs(n)) | |
} | |
xs.get(3) | |
xs.get(2) | |
/* === */ | |
val xs = 1 to 10 | |
xs.map(x => (x, 1 << x)) | |
val langs = List( | |
"scala", | |
"haskell", | |
"python", | |
"javascript", | |
"haskell", | |
"c#" | |
) | |
val resp = langs.map{ | |
case "scala" | "haskell" => ":-)" | |
case "python" => ":-|" | |
case _ => ":-()" | |
} | |
langs.zip(resp) | |
def fill[T](v: T, n: Int): List[T] = { | |
def loop(acc: List[T], x: Int): List[T] = { | |
if (x == 0) acc | |
else loop(v :: acc, x - 1) | |
} | |
loop(Nil, n) | |
} | |
fill("*", 5) | |
def decode[T](xs: List[(T, Int)]): List[T] = | |
xs.flatMap{ | |
case (l, n) => fill(l, n) | |
} | |
decode(List(("a", 2), ("b", 3), ("c", 1))) == | |
List("a", "a", "b", "b", "b", "c") | |
val xs = List(16, 17, 18, 20, 20) | |
xs.filter(_ >= 18) | |
xs.flatMap(x => | |
if(x >= 18) List(x) | |
else List(x, x) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
reference: http://aperiodic.net/phil/scala/s-99/