functional programming

Oct 9th, 2020 (edited)
1,041
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. // Functional Programming
2.
3. def incAll(list: List[Int]): List[Int] = {
4.     if(list.isEmpty) List.empty[Int]
6. }
7.
8. def incAllBy10(list: List[Int]): List[Int] = {
9.     if(list.isEmpty) List.empty[Int]
11. }
12.
13. // Or you can make a more adaptable version by adding a parameter
14. def incAll(byNum:Int, list:List[Int]): List[Int] = {
15.     if(list.isEmpty) List.empty[Int]
16.     else list.head+byNum :: incAll(byNum, list.tail)
17. }
18. def incAllBy10(list) = incAll(10, list)
19.
20. // In this one the operator is different too
21. def doubleNums(list) =
22.     if(list.isEmpty) List.empty[Int]
24.
25. // ok so let's do like an interpreter or some shit
26. def map(f: Int -> Int, list: List[Int]): List[Int] = {
27.     if(list.isEmpty) List.empty[Int]
28.     else f(list.head) :: map(f, list.tail)
29. }
30. def incAll(list) = map(x -> x+1, list)
31. def doubleNums(list) = map(x -> x*2, list)
32. def absNums(list) = map(x -> x.abs, list)
33. // this is called a lambda or anonymous function
34. // x -> x+1 is a function that takes x and returns x+1
35.
36. /*
37. Functional Programming - taking functions seriously
38. - Functions as first-class entities
39.
40. - we can put an int into a variable
41. - we can pass an int into a function
42. - we can return an int from a function
43. - we can store ints in data structures like list array etc
44. */
45.
46. // going back to the map() function
47.
48. def capitalize(list: List[String]): List[String] = map(str -> str.toUpperCase(), list)
49.
50. // we can add map[A] to account for type parameter
51. def map[A](f: A -> A, list: List[A]): List[A] = {
52.     if(list.isEmpty) List.empty[Int]
53.     else f(list.head) :: map(f, list.tail)
54. }
55.
56. def convert(list: List[String]): List[Int] = map(str -> str.toInt, list)
57.
58. // can also use
59. _ + 1
61. x -> x+1
62.
63. // also this
64. (x,y) -> y + x*2
RAW Paste Data