Capabilities of foldLeft of Scala
object FoldLeft extends App { | |
def reverse(list: List[Int]): List[Int] = | |
list.foldLeft[List[Int]](Nil)((acc, element) => element :: acc) | |
def dedupe(list: List[Int]): List[Int] = { | |
list.foldLeft[List[Int]](Nil)((acc, element) => if (acc.contains(element)) acc else acc :+ element) | |
} | |
def span(list: List[Int], p1: Int => Boolean, p2: Int => Boolean, p3: Int => Boolean, p4: Int => Boolean): (List[Int], List[Int], List[Int], List[Int]) = | |
list.foldLeft[(List[Int], List[Int], List[Int], List[Int])]((Nil, Nil, Nil, Nil)) { case ((p1List, p2List, p3List, p4List), element) => | |
( | |
if (p1(element)) p1List :+ element else p1List, | |
if (p2(element)) p2List :+ element else p2List, | |
if (p3(element)) p3List :+ element else p3List, | |
if (p4(element)) p4List :+ element else p4List | |
) | |
} | |
def combine(list1: List[Int], list2: List[Int]) = | |
list2.foldLeft[List[Int]](list1)((acc, element) => acc :+ element) | |
def zip(list1: List[Int], list2: List[String]): List[(Int, String)] = | |
if (list1.length > list2.length) { | |
list2.foldLeft[(List[Int], List[(Int, String)])]((list1, Nil)) { | |
case ((list, zip), element) => (list.tail, zip :+ (list.head, element)) | |
}._2 | |
} else { | |
list1.foldLeft[(List[String], List[(Int, String)])]((list2, Nil)) { | |
case ((list, zip), element) => (list.tail, zip :+ (element, list.head)) | |
}._2 | |
} | |
def unzip(list: List[(Int, String)]): (List[Int], List[String]) = | |
list.foldLeft[(List[Int], List[String])]((Nil, Nil)) { | |
case ((list1, list2), (number, str)) => (list1 :+ number, list2 :+ str) | |
} | |
def sort(list: List[Int]): List[Int] = | |
list.foldLeft[List[Int]](Nil) { (acc, element) => insert(element, acc) } | |
def insert(elem: Int, list: List[Int]): List[Int] = | |
list match { | |
case head :: tail => if (head <= elem) head :: insert(elem, tail) else elem :: list | |
case Nil => elem :: Nil | |
} | |
def sum(list: List[Int]): Int = list.foldLeft(0)(_ + _) | |
def map(list: List[Int], f: Int => Int): List[Int] = | |
list.foldLeft[List[Int]](Nil)((acc, element) => acc :+ f(element)) | |
def flatMap(list: List[Int], f: Int => List[Int]): List[Int] = | |
list.foldLeft[List[Int]](Nil)((acc, element) => acc ++ f(element)) | |
println(" ----" + flatMap(List(2, 3, 4, 4, 1), a => List(a * a))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment