Last active
August 2, 2019 15:52
-
-
Save xodhx4/3f45a13b4dd4390f23bbd46649f54aba to your computer and use it in GitHub Desktop.
[Scala functional Example] Examples of scala code that doing map, reduce, and filter #example #scala
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
/*filter | |
//Filter array by their index using collect | |
//EX) Get part of array that its index is even | |
*/ | |
// arr is List[Int] | |
val evenArr = arr | |
.zipWithIndex | |
.collect { | |
case (vali, ind) if (ind%2==1) => vali | |
} |
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
/*reduce | |
//Sum of List that is only odd | |
*/ | |
def f(arr:List[Int]):Int = arr.filter((i: Int) => i%2==1).reduceLeft(_ + _) |
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
//map | |
//Read string, split them, and make them Int | |
*/ | |
val real = StdIn.readLine() | |
val exp = StdIn.readLine() | |
/* Input is | |
//9 6 2015 | |
//6 6 2015 | |
*/ | |
val realArray = real.split(" ").map(x => x.toInt) | |
val expArray = exp.split(" ").map(x => x.toInt) | |
//return is Array(9, 6, 2015) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment