Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Functional Programming
- def incAll(list: List[Int]): List[Int] = {
- if(list.isEmpty) List.empty[Int]
- else list.head+1 :: incAll(list.tail)
- }
- def incAllBy10(list: List[Int]): List[Int] = {
- if(list.isEmpty) List.empty[Int]
- else list.head+10 :: incAll(list.tail)
- }
- // Or you can make a more adaptable version by adding a parameter
- def incAll(byNum:Int, list:List[Int]): List[Int] = {
- if(list.isEmpty) List.empty[Int]
- else list.head+byNum :: incAll(byNum, list.tail)
- }
- def incAllBy10(list) = incAll(10, list)
- // In this one the operator is different too
- def doubleNums(list) =
- if(list.isEmpty) List.empty[Int]
- else list.head*2 :: doubleNums(list.tail)
- // ok so let's do like an interpreter or some shit
- def map(f: Int -> Int, list: List[Int]): List[Int] = {
- if(list.isEmpty) List.empty[Int]
- else f(list.head) :: map(f, list.tail)
- }
- def incAll(list) = map(x -> x+1, list)
- def doubleNums(list) = map(x -> x*2, list)
- def absNums(list) = map(x -> x.abs, list)
- // this is called a lambda or anonymous function
- // x -> x+1 is a function that takes x and returns x+1
- /*
- Functional Programming - taking functions seriously
- - Functions as first-class entities
- - we can put an int into a variable
- - we can pass an int into a function
- - we can return an int from a function
- - we can store ints in data structures like list array etc
- */
- // going back to the map() function
- def capitalize(list: List[String]): List[String] = map(str -> str.toUpperCase(), list)
- // we can add map[A] to account for type parameter
- def map[A](f: A -> A, list: List[A]): List[A] = {
- if(list.isEmpty) List.empty[Int]
- else f(list.head) :: map(f, list.tail)
- }
- def convert(list: List[String]): List[Int] = map(str -> str.toInt, list)
- // can also use
- _ + 1
- // instead of
- x -> x+1
- // also this
- (x,y) -> y + x*2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement