progs/lecture1.scala
changeset 202 f7bcb27d1940
parent 200 01ee4b576eb2
child 247 50a3b874008a
equal deleted inserted replaced
201:018b9c12ee1f 202:f7bcb27d1940
     3 
     3 
     4 // Value assignments
     4 // Value assignments
     5 // (their names should be lower case)
     5 // (their names should be lower case)
     6 //====================================
     6 //====================================
     7 
     7 
       
     8 
     8 val x = 42
     9 val x = 42
     9 val y = 3 + 4
    10 val y = 3 + 4
    10 val z = x / y
    11 val z = x / y
    11 
       
    12 
    12 
    13 // (you cannot reassign values: z = 9 will give an error)
    13 // (you cannot reassign values: z = 9 will give an error)
    14 
    14 
    15 
    15 
    16 // Hello World
    16 // Hello World
    55 // Equality is structural
    55 // Equality is structural
    56 //========================
    56 //========================
    57 val a = "Dave"
    57 val a = "Dave"
    58 val b = "Dave"
    58 val b = "Dave"
    59 
    59 
    60 if (a == b) println("equal") else println("unequal")
    60 if (a == b) println("Equal") else println("Unequal")
    61 
    61 
    62 Set(1,2,3) == Set(3,1,2)
    62 Set(1,2,3) == Set(3,1,2)
    63 List(1,2,3) == List(3,1,2)
    63 List(1,2,3) == List(3,1,2)
    64 
    64 
       
    65 val n1 = 3 + 7
       
    66 val n2 = 5 + 5
       
    67 
       
    68 n1 == n2
    65 
    69 
    66 // this applies to "concrete" values;
    70 // this applies to "concrete" values;
    67 // you cannot compare functions
    71 // you cannot compare functions
    68 
    72 
    69 
    73 
    75 val tst = "This is a " + "test\n" 
    79 val tst = "This is a " + "test\n" 
    76 println(tst)
    80 println(tst)
    77 
    81 
    78 val lst = List(1,2,3,1)
    82 val lst = List(1,2,3,1)
    79 
    83 
       
    84 
    80 println(lst.toString)
    85 println(lst.toString)
    81 println(lst.mkString("\n"))
    86 println(lst.mkString(","))
    82 
    87 
    83 println(lst.mkString(", "))
    88 println(lst.mkString(", "))
    84 
    89 
    85 // some methods take more than one argument
    90 // some methods take more than one argument
    86 println(lst.mkString("[", ",", "]"))
    91 println(lst.mkString("{", ",", "}"))
    87 
    92 
    88 
    93 
    89 
    94 
    90 // Conversion methods
    95 // Conversion methods
    91 //====================
    96 //====================
    92 
    97 
    93 List(1,2,3,1).toString
    98 List(1,2,3,1).toString
    94 List(1,2,3,1).toSet
    99 List(1,2,3,1).toSet
    95 "hello".toList
   100 "hello".toList.tail
    96 1.toDouble
   101 1.toDouble
    97 
   102 
    98 
   103 
    99 // useful list methods
   104 // useful list methods
   100 
   105 
   106 List(1,2,3,4).take(2).sum
   111 List(1,2,3,4).take(2).sum
   107 List(1,2,3,4).drop(2).sum
   112 List(1,2,3,4).drop(2).sum
   108 List(1,2,3,4,3).indexOf(3)
   113 List(1,2,3,4,3).indexOf(3)
   109 
   114 
   110 "1,2,3,4,5".split(",").mkString("\n")
   115 "1,2,3,4,5".split(",").mkString("\n")
       
   116 "1,2,3,4,5".split(",").toList
   111 "1,2,3,4,5".split(",3,").mkString("\n")
   117 "1,2,3,4,5".split(",3,").mkString("\n")
   112 
   118 
   113 "abcdefg".startsWith("abc")
   119 "abcdefg".startsWith("abc")
   114 
   120 
   115 
   121 
   153 
   159 
   154 def incr(x: Int) : Int = x + 1
   160 def incr(x: Int) : Int = x + 1
   155 def double(x: Int) : Int = x + x
   161 def double(x: Int) : Int = x + x
   156 def square(x: Int) : Int = x * x
   162 def square(x: Int) : Int = x * x
   157 
   163 
       
   164 def str(x: Int) : String = x.toString
   158 square(6)
   165 square(6)
   159 
   166 
   160 
   167 
   161 // The general scheme for a function: you have to give a type 
   168 // The general scheme for a function: you have to give a type 
   162 // to each argument and a return type of the function
   169 // to each argument and a return type of the function
   170 // BTW: no returns!!
   177 // BTW: no returns!!
   171 // "last" line (expression) in a function determines the result
   178 // "last" line (expression) in a function determines the result
   172 //
   179 //
   173 
   180 
   174 def silly(n: Int) : Int = {
   181 def silly(n: Int) : Int = {
   175   n * n
   182   if (n < 10) n * n
   176   n + n
   183   else n + n
   177 }
   184 }
   178 
   185 
   179 
   186 
   180 // If-Conditionals
   187 // If-Conditionals
   181 //=================
   188 //=================
   209     if (n == 1) 1 else fib(n - 1) + fib(n - 2)
   216     if (n == 1) 1 else fib(n - 1) + fib(n - 2)
   210 
   217 
   211 
   218 
   212 //gcd - Euclid's algorithm
   219 //gcd - Euclid's algorithm
   213 
   220 
   214 def gcd(a: Int, b: Int) : Int =
   221 def gcd(a: Int, b: Int) : Int = {
   215   if (b == 0) a else gcd(b, a % b)
   222   if (b == 0) a 
       
   223   else {
       
   224     val foo = 42
       
   225     gcd(b, a % b)
       
   226   }  
       
   227 }
   216 
   228 
   217 gcd(48, 18)
   229 gcd(48, 18)
   218 
   230 
   219 
   231 
   220 def power(x: Int, n: Int) : Int =
   232 def power(x: Int, n: Int) : Int =
   243 //  Try(something).getOrElse(what_to_do_in_case_of_an_exception)
   255 //  Try(something).getOrElse(what_to_do_in_case_of_an_exception)
   244 //
   256 //
   245 import scala.util._
   257 import scala.util._
   246 import io.Source
   258 import io.Source
   247 
   259 
   248 val my_url = "https://nms.kcl.ac.uk/christian.urban/"
   260 val my_url = "https://nms.imperial.ac.uk/christian.urban/"
   249 
   261 
   250 Source.fromURL(my_url).mkString
   262 Source.fromURL(my_url).mkString
   251 
   263 
   252 Try(Source.fromURL(my_url).mkString).getOrElse("")
   264 Try(Source.fromURL(my_url).mkString).getOrElse("")
   253 
   265 
   254 Try(Some(Source.fromURL(my_url).mkString)).getOrElse(None)
   266 Try(Some(Source.fromURL(my_url).mkString)).getOrElse(None)
   255 
   267 
   256 
   268 
   257 // the same for files
   269 // the same for files
   258 Source.fromFile("test.txt").mkString
   270 Try(Some(Source.fromFile("text.txt").mkString)).getOrElse(None)
   259 
   271 
   260 // function reading something from files...
   272 // function reading something from files...
   261 
   273 
   262 def get_contents(name: String) : List[String] = 
   274 def get_contents(name: String) : List[String] = 
   263   Source.fromFile(name).getLines.toList
   275   Source.fromFile(name).getLines.toList
   264 
   276 
   265 get_contents("test.txt")
   277 get_contents("test.txt")
   266 
   278 
   267 // slightly better - return Nil
   279 // slightly better - return Nil
   268 def get_contents(name: String) : List[String] = 
   280 def get_contents(name: String) : List[String] = 
   269   Try(Source.fromFile(name).getLines.toList).getOrElse(Nil)
   281   Try(Source.fromFile(name).getLines.toList).getOrElse(List())
   270 
   282 
   271 get_contents("text.txt")
   283 get_contents("text.txt")
   272 
   284 
   273 // much better - you record in the type that things can go wrong 
   285 // much better - you record in the type that things can go wrong 
   274 def get_contents(name: String) : Option[List[String]] = 
   286 def get_contents(name: String) : Option[List[String]] = 
   311 
   323 
   312 
   324 
   313 // For-Comprehensions (not For-Loops)
   325 // For-Comprehensions (not For-Loops)
   314 //====================================
   326 //====================================
   315 
   327 
   316 for (n <- (1 to 10).toList) yield square(n)
   328 
       
   329 for (n <- (1 to 10).toList) yield { 
       
   330   square(n) + 1
       
   331 }
   317 
   332 
   318 for (n <- (1 to 10).toList; 
   333 for (n <- (1 to 10).toList; 
   319      m <- (1 to 10).toList) yield m * n
   334      m <- (1 to 10).toList) yield m * n
   320 
   335 
   321 
   336 
   322 val mult_table = 
   337 val mult_table = 
   323   for (n <- (1 to 10).toList; 
   338   for (n <- (1 to 10).toList; 
   324        m <- (1 to 10).toList) yield m * n
   339        m <- (1 to 10).toList) yield m * n
   325 
   340 
       
   341 println(mult_table.mkString)
   326 mult_table.sliding(10,10).mkString("\n")
   342 mult_table.sliding(10,10).mkString("\n")
   327 
   343 
   328 // the list/set/... can also be constructed in any 
   344 // the list/set/... can also be constructed in any 
   329 // other way
   345 // other way
   330 for (n <- List(10,12,4,5,7,8,10)) yield n * n
   346 for (n <- Set(10,12,4,5,7,8,10)) yield n * n
   331 
   347 
   332 
   348 
   333 // with if-predicates / filters
   349 // with if-predicates / filters
   334 
   350 
   335 for (n <- (1 to 3).toList; 
   351 for (n <- (1 to 3).toList; 
   336      m <- (1 to 3).toList;
   352      m <- (1 to 3).toList;
   337      if (n + m) % 2 == 0) yield (n, m)
   353      if (n + m) % 2 == 0;
       
   354      if (n * m) < 2) yield (n, m)
   338 
   355 
   339 for (n <- (1 to 3).toList; 
   356 for (n <- (1 to 3).toList; 
   340      m <- (1 to 3).toList;
   357      m <- (1 to 3).toList;
   341      if ((n + m) % 2 == 0)) yield (n, m)
   358      if ((((n + m) % 2 == 0)))) yield (n, m)
   342 
   359 
   343 // with patterns
   360 // with patterns
   344 
   361 
   345 val lst = List((1, 4), (2, 3), (3, 2), (4, 1))
   362 val lst = List((1, 4), (2, 3), (3, 2), (4, 1))
   346 
   363 
   386 for (n <- (1 to 10)) println(n)
   403 for (n <- (1 to 10)) println(n)
   387 
   404 
   388 
   405 
   389 // BTW: a roundabout way of printing out a list, say
   406 // BTW: a roundabout way of printing out a list, say
   390 val lst = ('a' to 'm').toList
   407 val lst = ('a' to 'm').toList
       
   408 
       
   409 for (n <- lst) println(n)
   391 
   410 
   392 for (i <- (0 until lst.length)) println(lst(i))
   411 for (i <- (0 until lst.length)) println(lst(i))
   393 
   412 
   394 // Why not just? Why making your life so complicated?
   413 // Why not just? Why making your life so complicated?
   395 for (c <- lst) println(c)
   414 for (c <- lst) println(c)