15
|
1 |
|
8
|
2 |
// webpages
|
14
|
3 |
|
|
4 |
|
18
|
5 |
//**Assignments (values)**
|
|
6 |
//(variable names should be lower case)
|
|
7 |
//=====================================
|
14
|
8 |
val x = 42
|
|
9 |
val y = 3 + 4
|
|
10 |
|
|
11 |
|
|
12 |
//**Collections**
|
|
13 |
//===============
|
|
14 |
List(1,2,3,1)
|
|
15 |
Set(1,2,3,1)
|
|
16 |
|
|
17 |
1 to 10
|
|
18 |
(1 to 10).toList
|
|
19 |
|
|
20 |
(1 until 10).toList
|
|
21 |
|
18
|
22 |
// an element in a list
|
|
23 |
List(1,2,3,1)(0)
|
|
24 |
List(1,2,3,1)(3)
|
|
25 |
|
14
|
26 |
|
|
27 |
//**Printing/Strings**
|
|
28 |
//====================
|
|
29 |
|
|
30 |
println("test")
|
15
|
31 |
|
|
32 |
|
14
|
33 |
val tst = "This is a " + "test"
|
|
34 |
println(tst)
|
|
35 |
|
|
36 |
val lst = List(1,2,3,1)
|
|
37 |
|
|
38 |
println(lst.toString)
|
|
39 |
println(lst.mkString("\n"))
|
|
40 |
|
|
41 |
// some methods take more than one argument
|
|
42 |
println(lst.mkString("[",",","]"))
|
|
43 |
|
|
44 |
//**Conversion methods**
|
|
45 |
//======================
|
|
46 |
|
|
47 |
List(1,2,3,1).toString
|
|
48 |
List(1,2,3,1).toSet
|
|
49 |
"hello".toList
|
|
50 |
1.toDouble
|
|
51 |
|
|
52 |
//**Types**
|
|
53 |
//=========
|
|
54 |
|
|
55 |
// Int, Long, BigInt
|
|
56 |
// String, Char
|
|
57 |
// List[Int], Set[Double]
|
|
58 |
// Pairs: (Int, String)
|
|
59 |
// List[(BigInt, String)]
|
12
|
60 |
|
|
61 |
|
14
|
62 |
//**Smart Strings**
|
|
63 |
//=================
|
|
64 |
""" """
|
|
65 |
|
|
66 |
//**Pairs/Tuples**
|
|
67 |
//================
|
|
68 |
|
|
69 |
val p = (1, "one")
|
|
70 |
p._1
|
|
71 |
p._2
|
|
72 |
|
|
73 |
val t = (4,1,2,3)
|
|
74 |
t._4
|
|
75 |
|
|
76 |
//**Function Definitions**
|
|
77 |
//========================
|
|
78 |
|
|
79 |
def square(x: Int): Int = x * x
|
|
80 |
|
|
81 |
//**Ifs control structures**
|
|
82 |
//==========================
|
|
83 |
|
|
84 |
def fact(n: Int): Int =
|
|
85 |
if (n == 0) 1 else n * fact(n - 1)
|
|
86 |
|
|
87 |
|
15
|
88 |
|
|
89 |
|
|
90 |
|
14
|
91 |
def fact2(n: BigInt): BigInt =
|
|
92 |
if (n == 0) 1 else n * fact2(n - 1)
|
|
93 |
|
|
94 |
def fib(n: Int): Int =
|
|
95 |
if (n == 0) 1 else
|
|
96 |
if (n == 1) 1 else fib(n - 1) + f(n - 2)
|
|
97 |
|
|
98 |
|
|
99 |
//a recursive function
|
|
100 |
def gcd(x: Int, y: Int): Int = 2 //???
|
|
101 |
|
15
|
102 |
//**String Interpolations**
|
|
103 |
//=========================
|
14
|
104 |
|
|
105 |
|
|
106 |
//**Assert/Testing**
|
|
107 |
====================
|
|
108 |
|
|
109 |
//**For-Maps (not For-Loops)**
|
|
110 |
//============================
|
|
111 |
|
|
112 |
for (n <- (1 to 10).toList) yield square(n)
|
|
113 |
|
|
114 |
for (n <- (1 to 10).toList; m <- (1 to 10).toList) yield m * n
|
|
115 |
|
|
116 |
val mtable = for (n <- (1 to 10).toList; m <- (1 to 10).toList) yield m * n
|
|
117 |
|
|
118 |
mtable.sliding(10,10).toList.mkString(
|