added lesson 5

This commit is contained in:
2025-03-20 07:47:30 +01:00
parent 9eeb59f1e0
commit 2f72fbb599
2 changed files with 26 additions and 1 deletions

19
src/Lesson5/Ex5_2.sc Normal file
View File

@ -0,0 +1,19 @@
def length[A](x: List[A]): Int = {
x.foldRight(0)((elem: A, len: Int) => len + 1)
}
def map[A, B](x: List[A], f: A => B): List[B] = {
x.foldRight(List.empty[B])((elem: A, list: List[B]) => f(elem)::list)
}
def dup[A](l: List[A]): List[A] = {
l.flatMap(e => List(e, e))
}
def dup2[A](l: List[A]): List[A] = {
l.foldRight(List.empty[A])((e, l) => e::e::l)
}
length(1::2::3::4::Nil)
map(1::2::3::4::Nil, (x: Int) => x * 2)
dup(1::2::3::Nil)