added lesson 5
This commit is contained in:
19
src/Lesson5/Ex5_2.sc
Normal file
19
src/Lesson5/Ex5_2.sc
Normal 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)
|
Reference in New Issue
Block a user