progs/lecture4.scala
changeset 455 557d18cce0f0
parent 450 61eb4f9b8d84
child 481 e03a0100ec46
equal deleted inserted replaced
454:289b85843ffd 455:557d18cce0f0
   122 // You do not want to write functions like contains, first, 
   122 // You do not want to write functions like contains, first, 
   123 // length and so on for every type of lists.
   123 // length and so on for every type of lists.
   124 
   124 
   125 def length_int_list(lst: List[Int]): Int = lst match {
   125 def length_int_list(lst: List[Int]): Int = lst match {
   126   case Nil => 0
   126   case Nil => 0
   127   case x::xs => 1 + length_int_list(xs)
   127   case _::xs => 1 + length_int_list(xs)
   128 }
   128 }
   129 
   129 
   130 length_int_list(List(1, 2, 3, 4))
   130 length_int_list(List(1, 2, 3, 4))
   131 
   131 
   132 def length_string_list(lst: List[String]): Int = lst match {
   132 def length_string_list(lst: List[String]): Int = lst match {
   144   case x::xs => 1 + length(xs)
   144   case x::xs => 1 + length(xs)
   145 }
   145 }
   146 length(List("1", "2", "3", "4"))
   146 length(List("1", "2", "3", "4"))
   147 length(List(1, 2, 3, 4))
   147 length(List(1, 2, 3, 4))
   148 
   148 
   149 length[Int](List(1, 2, 3, 4))
   149 
       
   150 length[String](List(1, 2, 3, 4))
   150 
   151 
   151 
   152 
   152 def map[A, B](lst: List[A], f: A => B): List[B] = lst match {
   153 def map[A, B](lst: List[A], f: A => B): List[B] = lst match {
   153   case Nil => Nil
   154   case Nil => Nil
   154   case x::xs => f(x)::map(xs, f) 
   155   case x::xs => f(x)::map(xs, f) 
   539 //     "HAL".increment
   540 //     "HAL".increment
   540 //
   541 //
   541 // you can avoid ugly fudges, like a MyString, by
   542 // you can avoid ugly fudges, like a MyString, by
   542 // using implicit conversions.
   543 // using implicit conversions.
   543 
   544 
       
   545 print("\n")
       
   546 print("""\n""")
   544 
   547 
   545 implicit class MyString(s: String) {
   548 implicit class MyString(s: String) {
   546   def increment = s.map(c => (c + 1).toChar) 
   549   def increment = s.map(c => (c + 1).toChar) 
   547 }
   550 }
   548 
   551 
   549 "HAL".increment.map(_.toInt)
   552 "HAL".increment
   550 
   553 
   551 
   554 
   552 // Abstract idea:
   555 // Abstract idea:
   553 // In that version implicit conversions were used to solve the 
   556 // In that version implicit conversions were used to solve the 
   554 // late extension problem; namely, given a class C and a class T, 
   557 // late extension problem; namely, given a class C and a class T,