progs/lecture2.scala
changeset 278 0c2481cd8b1c
parent 268 e43f7e92ba26
child 309 b192bc772613
equal deleted inserted replaced
277:acaf2099406a 278:0c2481cd8b1c
   511                   Clown)
   511                   Clown)
   512 
   512 
   513 println(people.sortWith(superior).mkString("\n"))
   513 println(people.sortWith(superior).mkString("\n"))
   514 
   514 
   515 
   515 
       
   516 // String interpolations as patterns
       
   517 
       
   518 val date = "2000-01-01"
       
   519 val s"$year-$month-$day" = date
       
   520 
       
   521 def parse_date(date: String) = date match {
       
   522   case s"$year-$month-$day" => Some((year.toInt, month.toInt, day.toInt))
       
   523   case s"$day/$month/$year" => Some((year.toInt, month.toInt, day.toInt))
       
   524   case _ => None
       
   525 } 
       
   526 
       
   527 
   516 // Tail Recursion
   528 // Tail Recursion
   517 //================
   529 //================
   518 
   530 
   519 
   531 
   520 def fact(n: Long): Long = 
   532 def fact(n: Long): Long = 
   721 
   733 
   722 
   734 
   723 
   735 
   724 
   736 
   725 
   737 
       
   738 // if you like verbosity, you can full-specify the literal. 
       
   739 // Don't go telling that to people, though
       
   740 (1 to 100).filter((x: Int) => x % 2 == 0).sum 
       
   741 
       
   742 // As x is known to be an Int anyway, you can omit that part
       
   743 (1 to 100).filter(x => x % 2 == 0).sum
       
   744 
       
   745 // As each parameter (only x in this case) is passed only once
       
   746 // you can use the wizardy placeholder syntax
       
   747 (1 to 100).filter(_ % 2 == 0).sum
       
   748 
       
   749 // But if you want to re-use your literal, you can also put it in a value
       
   750 // In this case, explicit types are required because there's nothing to infer from
       
   751 val isEven: (x: Int) => x % 2 == 0
       
   752 (1 to 100).filter(isEven).sum