From 8c01471ddab8f632fc5116fc8738c54fcd4637ca Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Thu, 20 Mar 2025 08:11:00 +0100 Subject: [PATCH] added assignment 5 ex 2 --- src/Assignment5/Folds.sc | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/Assignment5/Folds.sc diff --git a/src/Assignment5/Folds.sc b/src/Assignment5/Folds.sc new file mode 100644 index 0000000..3d8c957 --- /dev/null +++ b/src/Assignment5/Folds.sc @@ -0,0 +1,36 @@ +def areTrue(booleans: List[Boolean]): Boolean = { + booleans.foldLeft(true)((acc, value) => acc && value) +} + +def lString(strings: List[String]): Int = { + strings.foldLeft(0)((len, str) => len + str.length) +} + +def longest(strings: List[String]): Int = { + strings.foldLeft(0)((maxLen, str) => if (str.length > maxLen) str.length else maxLen) +} + +def isPresent[T](list: List[T], target: T): Boolean = { + list.foldLeft(false)((res, value) => res || value == target) +} + +def flattenList(list: List[Any]): List[Any] = { + list.foldRight(List.empty[Any])((elem, acc) => { + elem match { + case l: List[Any] => flattenList(l).foldRight(acc)((e, l) => e::l) + case _ => elem::acc + } + }) +} + +assert(!areTrue(List(true, true, false))) +assert(areTrue(List(true, true, true))) + +assert(lString(List("Folding", "is", "fun")) == 12) + +assert(longest(List("What", "is", "the", "longest?")) == 8) + +assert(!isPresent(List(1, 2, 3, 4), 5)) +assert(isPresent(List(1, 2, 3, 4), 3)) + +assert(flattenList(List(List(1, 1), 2, List(3, List(5, 8)))) == List(1, 1, 2, 3, 5, 8)) \ No newline at end of file