513 // nothing is perfect. |
513 // nothing is perfect. |
514 |
514 |
515 |
515 |
516 |
516 |
517 |
517 |
518 // Polymorphic Types |
518 |
519 //=================== |
519 |
520 |
|
521 // You do not want to write functions like contains, first |
|
522 // and so on for every type of lists. |
|
523 |
|
524 |
|
525 def length_string_list(lst: List[String]): Int = lst match { |
|
526 case Nil => 0 |
|
527 case x::xs => 1 + length_string_list(xs) |
|
528 } |
|
529 |
|
530 def length_int_list(lst: List[Int]): Int = lst match { |
|
531 case Nil => 0 |
|
532 case x::xs => 1 + length_int_list(xs) |
|
533 } |
|
534 |
|
535 length_string_list(List("1", "2", "3", "4")) |
|
536 length_int_list(List(1, 2, 3, 4)) |
|
537 |
|
538 //----- |
|
539 def length[A](lst: List[A]): Int = lst match { |
|
540 case Nil => 0 |
|
541 case x::xs => 1 + length(xs) |
|
542 } |
|
543 length(List("1", "2", "3", "4")) |
|
544 length(List(1, 2, 3, 4)) |
|
545 |
|
546 def map[A, B](lst: List[A], f: A => B): List[B] = lst match { |
|
547 case Nil => Nil |
|
548 case x::xs => f(x)::map_int_list(xs, f) |
|
549 } |
|
550 |
|
551 map_int_list(List(1, 2, 3, 4), square) |
|
552 |
|
553 |
|
554 |
|
555 |
|
556 |
|
557 |
|
558 // Cool Stuff |
|
559 //============ |
|
560 |
|
561 |
|
562 // Implicits |
|
563 //=========== |
|
564 // |
|
565 // For example adding your own methods to Strings: |
|
566 // Imagine you want to increment strings, like |
|
567 // |
|
568 // "HAL".increment |
|
569 // |
|
570 // you can avoid ugly fudges, like a MyString, by |
|
571 // using implicit conversions. |
|
572 |
|
573 |
|
574 implicit class MyString(s: String) { |
|
575 def increment = for (c <- s) yield (c + 1).toChar |
|
576 } |
|
577 |
|
578 "HAL".increment |
|
579 |
|
580 |
|
581 |
|
582 |
|
583 |
|
584 |
|