Created
January 10, 2018 07:33
-
-
Save harmeetsingh0013/1146cd95e10fc5d854704ea95554cb84 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
/* Custom Collection */ | |
import scala.collection.mutable.ArrayBuffer | |
case class CustomList[A](elements: A*) { | |
val elems = new ArrayBuffer[A] | |
elems ++= elements | |
def foreach(c: A => Unit): Unit = { | |
elems.foreach(c) | |
} | |
def map[B](f: A => B): CustomList[B] = { | |
val temp = elems.map(f) | |
CustomList(temp: _*) | |
} | |
def withFilter(p: A => Boolean): CustomList[A] = { | |
val temp = elems.filter(p) | |
CustomList(temp: _*) | |
} | |
def flatMap[B](f: A => CustomList[B]): CustomList[B] = { | |
val temp = elems.map(f) | |
flatternLike(temp) | |
} | |
def flatternLike[B](seq: Seq[CustomList[B]]): CustomList[B] = { | |
val temp = new ArrayBuffer[B] | |
for(i <- seq) { | |
for(j <- i) { | |
temp += j | |
} | |
} | |
CustomList(temp: _*) | |
} | |
} | |
/* MAIN */ | |
object ForExpression extends App { | |
val ints = CustomList(1, 2, 3) | |
for( i <- ints) { println(i)} | |
val values1: CustomList[Int] = for(i <- ints; a = (i + 1)) yield a | |
println(s"Map Values: $values1") | |
val values2 = for { | |
i <- ints | |
if(i % 2 == 0) | |
} yield i | |
println(s"With Filter Values: $values2") | |
val values3: CustomList[Int] = for(i <- ints; j <- ints; a = (i + j + 1)) yield a | |
println(s"FlatMap Values: $values3") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment