From 56f41ecc22fb107d8e7f989f58440c191e211ffc Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Thu, 20 Mar 2025 07:48:36 +0100 Subject: [PATCH] added assignment 5 ex 1 --- README.md | 8 ++++++++ src/Assignment5/HOFOnLists.sc | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 src/Assignment5/HOFOnLists.sc diff --git a/README.md b/README.md index 2c92f31..06990a4 100644 --- a/README.md +++ b/README.md @@ -81,3 +81,11 @@ - Binary tree - List functions - Predicates (any / every) + +### Assignment 5 - High-order functions on lists +[Files](src/Assignment5) +- High-order functions +- Lists +- Map +- Fold +- Zip \ No newline at end of file diff --git a/src/Assignment5/HOFOnLists.sc b/src/Assignment5/HOFOnLists.sc new file mode 100644 index 0000000..f146b6e --- /dev/null +++ b/src/Assignment5/HOFOnLists.sc @@ -0,0 +1,18 @@ +def lengthStrings(strings: List[String]): List[Int] = { + strings map (s => s.length) +} + +def dup[T](elem: T, n: Int): List[T] = { + (1 to n).toList map (_ => elem) +} + +def dot(list1: List[Int], list2: List[Int]): List[Int] = { + list1 zip list2 map (p => p._1 * p._2) +} + +assert(lengthStrings(List("How","long","are","we?")) == List(3, 4, 3, 3)) + +assert(dup("foo", 5) == List("foo", "foo", "foo", "foo", "foo")) +assert(dup(List(1,2,3), 2) == List(List(1,2,3), List(1,2,3))) + +assert(dot(List(1,2,3), List(2,4,3)) == List(2,8,9)) \ No newline at end of file