楼主: ReneeBK
1104 6

[Lecture Notes]Object-Oriented Software Development [推广有奖]

  • 1关注
  • 62粉丝

VIP

已卖:4897份资源

学术权威

14%

还不是VIP/贵宾

-

TA的文库  其他...

R资源总汇

Panel Data Analysis

Experimental Design

威望
1
论坛币
49635 个
通用积分
55.7537
学术水平
370 点
热心指数
273 点
信用等级
335 点
经验
57805 点
帖子
4005
精华
21
在线时间
582 小时
注册时间
2005-5-8
最后登录
2023-11-26

楼主
ReneeBK 发表于 2016-4-9 08:38:11 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
  • - Syllabus

二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:Development Oriented software Lecture Develop Software

沙发
ReneeBK 发表于 2016-4-9 08:44:05
  1. /*
  2.   CS:2820 Object Oriented Software Development
  3.   Spring 2015
  4.   The University of Iowa
  5.    
  6.    Instructor: Cesare Tinelli
  7. */

  8. /* Scala examples seen in class */


  9. /* Basic types */

  10. 3

  11. 3 + 5

  12. 4 - 2

  13. 3.0

  14. // some symbols are overloaded
  15. 1.4 + 3.0


  16. // implicit conversion

  17. 1.4 + 3   // syntactic sugar for

  18. 1.4 + 3.toDouble


  19. "hi"

  20. "hi" ++ " there"


  21. // ill-typed

  22. "hi" ++ 3


  23. "hi" + " there"

  24. // implicit conversion
  25. "high " + 5  // abbreviates

  26. "high " + 5.toString // functionally equivalent to

  27. "high " ++ "5"



  28. // implicit conversion and left associativity of +

  29. "hi" + 3.4 + 1  // implicitly converted to

  30. ("hi" + 3.4.toString) + 1.toString


  31. 3.4 + 1 + "hi" // implicitly converted to

  32. (3.4 + 1.toDouble).toString + "hi"



  33. true

  34. ! true

  35. true && false

  36. true || false


  37. 3 == 5 - 2

  38. 3 == 3.0 // implictly converted to

  39. 3.toDouble == 3.0

  40. 3 == "3" /** no implicity conversion here! **/


  41. /* tuple types */

  42. (1,3)

  43. (3,4,5)

  44. (3,"pp",4.3)

  45. ((1,2),3) == (1,(2,3))  // tuples of different type
  46. ((1,2),3) == (1,2,3)    // tuples of different type



  47. /* Unit type */

  48. ()

  49. val a = ()


  50. /* values and variables */

  51. val a = 3   // declares symbolic value a as a synonym for 3

  52. a

  53. a = 4  // error, symbolic values are immutable


  54. var b = 4  // declares a variable b

  55. b = 0  // variables are mutable


  56. /* Type ascription */

  57. val a:Int = 4  // prescribes right hand-side expression to have type Int

  58. val a:Int = 4.7  // will generate a type error

  59. val a:Float = 4  // will convert 4 to 4.0

  60. val a:String = "abc"  

  61. val a:String = 3 // type error

  62. 3:Int

  63. (3:Int) + 1

  64. 3:Long  // implicitly converted to

  65. (3.toLong):Long

  66. (3:Long) + 1 // implicitly converted to

  67. ((3.toLong):Long) + 1.toLong

  68. 3:String  // failed implict conversion, type error


  69. /* methods */


  70. // methods with automatically inferred return type
  71. def f1 (n:Int) = n + 1

  72. val a = 3

  73. f1(a)

  74. def f2 (n:Int) = n + 1.5


  75. f2(3)

  76. // method with return type Unit
  77. def g (n:Int) = println("Input value was " + n)

  78. // alternative syntax for Unit returning method
  79. def g (n:Int) {
  80.   println("Input value was " + n)
  81. }

  82. // g is interesting for its side effect (printing something),
  83. // not for its returned value
  84. val x = g(4)


  85. def max (x:Int, y:Int) = if (x > y) x else y
  86.   
  87. // parsed incorrectly
  88. // 'if' statement must be in a single line or
  89. // enclosed in a block (see later)
  90. def max (x:Int, y:Int) =
  91.   if (x > y)
  92.     x
  93.   else
  94.     y

  95. // correct syntax
  96. def max (x:Int, y:Int) = {
  97.   if (x > y)
  98.     x
  99.   else
  100.     y
  101. }


  102. var c = 3

  103. // The if construct is an expression.
  104. // It can be seen as a mixfix operator with three arguments:
  105. //
  106. //   if (_) _ else _
  107. //
  108. // The first argument must be of type Boolean.
  109. // The second and third argument must be of the same type.
  110. // The type of an if expression is determined by the type of its
  111. // second and third arguments
  112. //
  113. val k = if (c > 0) 10 else 20



  114. // if expressions can go everywhere an expression of can go
  115. (if (c > 0) 1 else 0) + 7



  116. // if the left and right branches are not of the same type
  117. // they are implicitly converted the their closest common supertype
  118. // (roughly speaking)
  119. if (true) 1 else 2.0

  120. if (true) 1 else "f"


  121. /* expressions with side effects */

  122. // assignments are also expressions ...
  123. c = 4

  124. // ... of type Unit
  125. :type (c = 4)

  126. val w = (c = 0)

  127. // this looks a lot like Jave code but it is an expression
  128. // (of type Unit)
  129. if (c > 0)  c = c + 1  else  c = c - 1



  130. /* sequential composition of expressions */

  131. // expressions can be composed and made into a block
  132. {3; 4}

  133. // block evaluates to and has the type of its last expression
  134. // in the sequence

  135. // a new line separator can be used instead of ;
  136. { 3
  137.   4
  138. }


  139. // zero or more espressions can be composed
  140. {}  // of type unit

  141. {3}

  142. {3; 4; "a"}

  143. // blocks are expressions and so can be nested
  144. {{3; 4}; 5}

  145. {3; {4; 5}}

  146. // composition is most useful with expressions with side effect,
  147. // such as assignments
  148. {c = 40; c}  // changes c and returns its value



  149. val x1 = {c = 42; c - 2}  // x1 is an Int

  150. c

  151. val x2 = {2; c = 41} // x2 is a Unit

  152. c

  153. // since blocks are expressions, they can be used as arguments
  154. // in method calls (not recommended for clarity though)
  155. f1({c = 3; 2})

  156. c
复制代码

藤椅
ReneeBK 发表于 2016-4-9 09:32:45
  1. /*
  2.   CS:2820 Object Oriented Software Development
  3.   Spring 2015
  4.   The University of Iowa
  5.    
  6.    Instructor: Cesare Tinelli
  7. */


  8. /* Scala examples seen in class */

  9. /* static scoping rules */

  10. val a = 10

  11. def f (x:Int) = a + x

  12. f(4)

  13. // *new* immutable variable a, distinct from the previous one
  14. val a = 100

  15. // the new a shadows the old one
  16. a

  17. // however, the old one is unchanged
  18. f(4)


  19. // blocks can contain both expression *and* (variable/method) definitions

  20. // variable k1 is visible only in the block in which it is declared

  21. {val k1 = 4
  22. k1*k1
  23. }

  24. k1 // error

  25. // within
  26. {val x = 4
  27. val x = 5
  28. x
  29. }


  30. // local declarations shadow less local ones
  31. val k = 1
  32. {val k = 2;
  33.   {val k = 3
  34.    println(k)
  35.   }
  36. println(k)
  37. }
  38. println(k)

  39. // there is no shadowing within the same block though
  40. {val x = 4
  41. val x = 5 // will generate an error
  42. x
  43. }


  44. // method definitions can have local scope too
  45. {def h(x:Int) = x + 1
  46. h(9)
  47. }

  48. h(9)  // error

  49. // this implies that methods can be defined locally
  50. // within other methods

  51. def f (x:Int) = {
  52. def square (x:Int) = x * x
  53. def double (x:Int) = x + x

  54. square(x) - double(x)
  55. }


  56. // Scala has while "statements" too.
  57. // As in the case of if, they are actually expressions of type Unit.
  58. // While can be seen a mixfix operator with two arguments:
  59. //
  60. //    while (_) _
  61. //
  62. // the first argument takes an expression of type bool,
  63. // the second takes any expression
  64. var j = 10

  65. while (j > 0)  j = j - 1


  66. val u = while (j > 0)  j = j - 1

  67. // the second argument of while can be a block
  68. j = 6

  69. while (j > 0) {
  70.         println(j)
  71.         j = j - 1
  72. }  

  73. // a block of two expressions, both of type Unit
  74. {
  75.         j = 8
  76.         while (j > 0) {
  77.          println(j)
  78.          j = j - 1
  79.         }
  80. }

  81. // The body of a method can be a block
  82. def print_range(m:Int, n:Int) = {
  83.   var i = m
  84.   println()
  85.   while (i <= n) {
  86.     print(i + " ")
  87.     i = i + 1
  88.   }
  89.   println()
  90. }

  91. print_range(4,9)


  92. // imperative-style definition of factorial function
  93. def fact (n:Int) = {
  94.   var i = n
  95.   var f = 1
  96.   while (i > 0) {
  97.     f = f * i
  98.     i = i - 1
  99.   }
  100.   f
  101. }

  102. // functional style, recursive definition of factorial
  103. def rfact (n:Int) = if (n <= 1) 1 else n * rfact(n-1)



  104. // declaring the return type of recursive methods is mandatory
  105. def rfact (n:Int):Int = {
  106. if (n <= 1)
  107.   1
  108. else
  109.   n * rfact(n-1)
  110. }





  111. /* Pattern matching */

  112. val t = (3,5,2)

  113. // declare three new variables x1,x2,x3;
  114. // the value of xi is the value of t's i-th component;
  115. // the pattern (x1,x2,x3) is matched against (3,5,2)
  116. val (x1,x2,x3) = t

  117. // _ is for "don't care" positions
  118. val (y1,y2,_) = t

  119. // pattern matching can be used with nested patterns
  120. val t = ((2,3),5,(6,2))

  121. val (_, x, _) = t
  122. val (_, _, (x,_)) = t


  123. // patterns are extremely useful with the match construct:
  124. //
  125. //    (_ match {case _ => _ ... case _ => _})
  126. //
  127. // the first argument of match is match agains the pattern given
  128. // between case and => ;
  129. // patterns are checked one at a time, top-down;
  130. // the value of the whole match construct is the value of the expression
  131. // on the right of the matching pattern
  132. var n = 1

  133. n match {
  134.   case 0 => "zero"
  135.   case 1 => "one"
  136.   case _ => "other"
  137. }
  138. // All right-hand sides of a 'case' clause must be of the same type


  139. // if all cases fail an exception is raised
  140. n match {
  141.   case 0 => "zero"
  142. }


  143. // match and patterns allow one to write cleaner and more compact code
  144. def convert (n:Int) =
  145.   n match {
  146.    case 0 => "zero"
  147.    case 1 => "one"
  148.    case _ => "other"
  149.   }
  150.   
  151. // the bodies of the case statements can be any expression (in particular a block)
  152. // but, like in the the two branches of the if construct, they all have to be of
  153. // same type  
  154. def p (n: Int) =
  155.   n match {
  156.     case 0 => {
  157.       print("You entered ")
  158.       println("zero")
  159.     } // type of this is Unit
  160.     case _ => {
  161.      print("You did not enter ")
  162.      println("zero")
  163.     } // type of this is Unit
  164.   }
  165.   
  166. // patterns can be complex and nested
  167. var v = (1, 2)

  168. v match {
  169.   case (0, 0) => "a"
  170.   case (0, _) => "b"
  171.   case (_, 0) => "c"
  172. }

  173. // bothZero returns "OK" if both of its arguments are 0
  174. // Otherwise it returns "NotOK"
  175. // common (bad) coding style
  176. def bothZero (x1:Int, x2:Int) = {
  177.   if (x1 == 0) {
  178.     if (x2 == 0)
  179.       "OK"
  180.     else
  181.       "NotOK"
  182.   }
  183.   else
  184.     "NotOK"
  185. }
  186.   
  187. // same method but using match

  188. def bothZero (x1:Int, x2:Int) =
  189.   (x1, x2) match {
  190.     case (0, 0) => "OK"
  191.     case _ => "NotOK"
  192.   }


  193. // the input here is already a pair that can be pattern matched
  194. // directly
  195. def bz (p:(Int, Int)) =
  196.   p match {
  197.     case (0, 0) => true
  198.     case _ => false
  199.   }

  200. def and (p:(Boolean, Boolean)) =
  201.   p match {
  202.     case (true, y) => y
  203.     case (false, _) => false
  204.   }
  205. // the scope of a pattern variable in a case is the body of that case

  206. def and (p:(Boolean, Boolean)) =
  207.   p match {
  208.     case (true, y) => y
  209.     case (false, _) => y // y is undefined here
  210.   }


  211. // factorial with match
  212. def fact (n:Int):Int =
  213.   n match {
  214.     case 0 => 1
  215.     case _ => n * fact(n - 1)
  216.   }
  217.   
  218. // you can match several values at the same time by putting them into a tuple

  219. (0 < 1, 1 == 1) match {
  220.   case (true, y) => y
  221.   case (false, _) => false
  222. }
  223.         
  224.         
  225. // the match construct too builds expressions

  226. val r = (0 < 1, 1 == 1) match {
  227.          case (true, y) => y
  228.          case (false, _) => false
  229.         }
复制代码

板凳
ReneeBK 发表于 2016-4-9 09:33:36
  1. /*
  2.   CS:2820 Object Oriented Software Development
  3.   Spring 2015
  4.   The University of Iowa
  5.    
  6.    Instructor: Cesare Tinelli
  7. */

  8. /* Scala examples seen in class */



  9. /* Collections: Lists */

  10. // lists are finite sequences of elements
  11. val l = List(1, 2, 3)

  12. // Main list methods
  13. l.head
  14. l.tail
  15. l.length

  16. // individual elements can be accessed with this syntax
  17. // with indices starting at zero (like in arrays)

  18. l(0)  // first element of l

  19. l(3)  // fourth element of l


  20. // a list can be built with elements of *any* type,
  21. // but all elements must be of the *same* type
  22. List('a', 'b')

  23. List("hi", "there")

  24. List((1, 2), (1, 4))

  25. List(List(1, 2), List(1, 4, 3))

  26. List(1, "a")   // types as a list of Any


  27. val l1 = List(1, 2, 3)
  28. val l2 = List(1, 2, 3)

  29. // list identity
  30. l1 eq l2   

  31. val l3 = l1

  32. l1 eq l3

  33. // structural equality
  34. l1 == l2  

  35. // order and number of occurrences of elements matters for equality
  36. List(1,2,3) == List(2,1,3)

  37. List(1,2) == List(1,2,2)



  38. // Empty list, prints as List()
  39. Nil

  40. // Evaluates to Nil
  41. List()

  42. Nil eq List()


  43. // bad practice, gives you a list of elements of type Nothing.
  44. val l = List()

  45. // recommended, specify the element type of an empty list explicitly
  46. val il = List[Int]()

  47. var x = List("a", "b")

  48. // Causes an implicit conversion of 1 and 2 to Long.
  49. var y = List[Long](1, 2)


  50. // if T1 and T2 are different types,
  51. // List[T1] is a different type from List[T2]
  52. // no implict conversions are defined for them
  53. x = il

  54. y = il


  55. // Lists are built by increasingly adding elements in front
  56. // of Nil with the "cons" operator ::
  57. val x = 6 :: Nil

  58. val y = 5 :: x

  59. // note that x is unchanged
  60. x

  61. y.tail eq x

  62. // :: is right associative.
  63. 3 :: 4 :: Nil
  64. // same as
  65. 3 :: (4 :: Nil)

  66. // List(3, 4) can be understood as syntactic sugar for
  67. 3 :: (4 :: Nil)



  68. 3 :: 4  // error, right-hand argument not a list

  69. // can mix and match notation
  70. 3 :: List(4)

  71. // note type here
  72. List(7) :: Nil



  73. val l = List(1, 2, 3)

  74. // invariant defining head and tail in terms of ::
  75. // for any non-empty list
  76. //
  77. (l.head :: l.tail) == l



  78. // pattern matching also works with ::
  79. val h :: t = l

  80. // why it works: l is really 1 :: (2 :: (3 :: Nil))
  81. val h :: t = 1 :: (2 :: (3 :: Nil))

  82. // deeper patters for lists with at least two elements
  83. val x1 :: x2 :: t = l

  84. val x1 :: x2 :: x3 :: t = l

  85. val x1 :: x2 :: x3 :: x4 :: t = l // fails because l has < 4 elements

  86. // 'List' syntax can also be used for pattern matching
  87. val List(x1, x2, x3) = l

  88. // fails because l has length 3
  89. val List(x1) = l

  90. // also fails
  91. val List(x1, x2) = List("a")



  92. // recursive definition of length function for lists
  93. // based on navigating the list structure.
  94. // If l is empty its length is 0. If l is non-empty,
  95. // and so has a tail t, its lenght is 1 + the length of t
  96. //
  97. def len (l: List[Int]): Int =
  98.   l match {
  99.     case Nil    => 0
  100.     case _ :: t => 1 + len(t)
  101.   }
  102.   
  103.   
  104. len(List(1, 1, 1))

  105. // min returns the minimun element of an non-empty integer list,
  106. // it raises an exception with empty lists
  107. //
  108. // if l has only one element n, the minimum is n
  109. // if l has at least two elements its miminum is the smaller
  110. // between l's head and the minimun of l's tail.
  111. //
  112. def min (l:List[Int]):Int =
  113.   l match {
  114.     case Nil => throw new IllegalArgumentException
  115.     case n :: Nil => n
  116.     case n :: t => {
  117.       val m = min(t)
  118.       if (n < m) n else m
  119.     }
  120.   }

  121. // concat contatenates two lists
  122. def concat(l:List[Int], m:List[Int]):List[Int] =
  123.   l match {
  124.     // when l is empty, its concatenation with m is just m
  125.     case Nil  => m
  126.     // when l has a head h and a tail t, its contatenation with m
  127.     // is obtained by inserting h in front of the contatenation
  128.     // of t with m
  129.     case h :: t => h :: concat(t, m)
  130.   }

  131. concat(List(1, 2), List(3, 4, 5))

  132. // the effect of concat is achieved with the predefined overloaded operator ++
  133. List(1,2) ++ List(3,4,5)

  134. // reverse reverses a list
  135. def reverse (l:List[Int]):List[Int] =
  136.   l match {
  137.     // when l is empty it is its own reverse
  138.     case Nil => l
  139.     // when l has a head h and a tail t, its reverse is the contatenation
  140.     // of the reverse of t with a list containing just h
  141.     case h :: t => {
  142.       val rt = reverse(t)
  143.       val lh = List(h)
  144.       concat(rt, lh)
  145.     }
  146.   }

  147. reverse(List(3, 4, 5))

  148. // more compact version of the implementation above
  149. // both version are inefficient because each reverse(t) is
  150. // scanned linearly by concat each time
  151. def reverse (l:List[Int]):List[Int] =
  152.   l match {
  153.     case Nil  => l
  154.     case h :: t => concat(reverse(t), List(h))
  155.   }
  156.   
  157. // this reverse uses a local auxiliary function rev
  158. // rev is "tail-recursive", it builds the reverse of l as it scans it
  159. // by incrementally moving its elements into an initially empty list rl.
  160. // l is scanned only once
  161. def reverse (x:List[Int]):List[Int] = {

  162.   def rev (l:List[Int], rl:List[Int]):List[Int] =
  163.   l match {
  164.     // when l has a head h and a tail t, put h in front of rl
  165.     // and continue with t and h::rl
  166.     case h :: t => rev(t, h :: rl)
  167.     // when l is Nil, rl contains by construction the reverse
  168.     // of the original list
  169.     case Nil => rl
  170.   }

  171.   rev(x, Nil)
  172. }
复制代码

报纸
ReneeBK 发表于 2016-4-9 09:34:12
  1. /*
  2.   CS:2820 Object Oriented Software Development
  3.   Spring 2015
  4.   The University of Iowa
  5.    
  6.    Instructor: Cesare Tinelli
  7. */



  8. /* Collection types: Arrays */

  9. // creates an array with 5 elements and calls it a
  10. val a = new Array(5)

  11. // more typically, one specifies the element type as well;
  12. // the array elements start with a type-dependent default value
  13. val a = new Array[Double](5)

  14. a[1]  // standard notation *not* used in Scala

  15. a(1)  // Scala's notation for array access

  16. a(0) = 2.5  //  array update

  17. a(5)  // generates out of bound error

  18. // generates an Array[Int] of length 3 and elements 10,11, and 12;
  19. // element type Int is inferred
  20. Array(10, 11, 12)

  21. val a = Array(10, 11, 12)

  22. // 3 different ways to generate an Array[Long]
  23. // from Int initial values
  24. val a = Array[Long](10, 11, 12)  // preferred one

  25. val a:Array[Long] = Array(10, 11, 12)

  26. val a = Array(10:Long, 11, 12)



  27. // note the tricky difference

  28. val a =     Array[Long](10)  // a is an Array[Long] with one element: 10

  29. val b = new Array[Long](10)  // n is an Array[Long] with 10 elements

  30. // array length
  31. a.length

  32. // multidimentional arrays are arrays of arrays
  33. val m = new Array[Array[Int]](10)

  34. val m = Array(Array(1, 2, 3),
  35.               Array(4, 5, 6),
  36.               Array(7, 8, 9),
  37.               Array(10, 11, 12))

  38. m(2)(1) // no special syntax for matrix access



  39. /* Scala examples seen in class */

  40. /* Built-in control structures */  

  41. /* for loops */

  42. // The for loop is an expression of type Unit
  43. // It can be seen as a mixfix operator with two arguments:
  44. //
  45. //   for (_) _
  46. //
  47. // The second argument (the "body") is any expression.
  48. // The first argument is a sequence of one or more *generators*
  49. // separated by ';'
  50. //
  51. // A generator is an expression of the form  _ <- _ where the first
  52. // argument is a pattern and the second is an expression of a collection
  53. // type (Range, List, Array, ...)

  54. // below, the pattern 3 is matched against each element of the list.
  55. // each time there is a match, the body of for is evaluated
  56. for (3 <- List(1,3,4,3,5,3,6,3))  println("Hi")

  57. // as in the match and val constructs, patterns can contain variables
  58. for (i <- List(1,2,14,52,7,10)) println("high five")

  59. // any variables in the pattern have local scope within the for
  60. for (i <- List(1,2,14,52,7,10)) println("i = " + i)

  61. i // gives an error


  62. // patterns in a generator can be arbitrarily complex, depending
  63. // on the type of the collection
  64. val l = List((1,2), (1,4), (6,7), (3,6))

  65. for ( (i, j) <- l )  println("i = " + i + ", j = " + j)  

  66. for ( (i, _) <- l )  println(i) // ignores the second component of each pair

  67. for ( (1, j) <- l )  println(j) // only matches pairs starting with 1


  68. // *any collection* type can be used in a generator
  69. for (i <- Array(1.2, 2.5, 4.5, 7.1)) println("i = " + i)

  70. for (i <- Set(1,2,4,5,7,10,4)) println("i = " + i)

  71. // even strings, which are seen as the collection of their characters
  72. for (i <- "abcd") println("i = " + i)

  73. // ranges are sequences of consecutive integers
  74. val r = Range(1,5) // contains values 1, 2, 3, 4

  75. for (i <- r) println("i = " + i)

  76. // Expression   1 to 4   is the same as Range(1,5)
  77. for (i <- 1 to 4) println("i = " + i)


  78. // Putting more than one generator has the effect of nested for loops
  79. for (i <- 1 to 2; j <- 1 to 3) println("i = " + i + ", j = " + j)

  80. // the above for has the same effect as
  81. for (i <- 1 to 2) {
  82.   for (j <- 1 to 3) println("i = " + i + ", j = " + j)
  83. }

  84. // and it can also be written as
  85. for {
  86.   i <- 1 to 2
  87.   j <- 1 to 3
  88. } println("i =" + i + ", j = " + j)


  89. // a generator can be optionally followed by a *filter* of the form: if b
  90. // where b is a Boolean expression.
  91. // the matched value is used if and only if b evaluates to true
  92. for (i <- List(1,9,2,4,5,7,10) if i > 4) println("i = " + i)

  93. val l = List((1,2), (1,4), (6,7), (3,6))

  94. for ( (i,j) <- l if j == 2*i )
  95.   println((i,j))


  96. for {
  97.   c1 <- "hi"
  98.   c2 <- "fifi"
  99.   if c1 == c2
  100. } println("character match found for letter " + c1)


  101. // BTW, matching filters can be used with the match construct too
  102. val l = List(2, 1, 3)

  103. l match {
  104.         case x :: y :: t if (x > y) =>  y :: x :: t
  105.         case _  =>  l
  106. }
  107. // the first case applies only if l has at least two elements *and*
  108. // its first element is greater than the second


  109. // this version of reverse scans the input list x using
  110. // a for loop instead of a recursive call,
  111. // each element of x is inserted into an initialy empty list;
  112. // a mutable variable is necessary to store the growing reversed list
  113. //
  114. def reverse(x:List[Int]):List[Int] = {
  115.   var l = List[Int]()
  116.   for (h <- x)  l = h :: l
  117.   l
  118. }
复制代码

地板
ReneeBK 发表于 2016-4-9 09:34:49
  1. /*
  2.   CS:2820 Object Oriented Software Development
  3.   Spring 2015
  4.   The University of Iowa
  5.    
  6.    Instructor: Cesare Tinelli
  7. */

  8. /* Classes and class instances */



  9. /* User-defined classes */

  10. // One can define new classes with the construct of the form
  11. //
  12. //  class Name(a1,...,an) { ... }
  13. //
  14. // where Name is an identifier for the class,
  15. // a1, ..., an for n >= 0  are any values
  16. // { ... } is the "body" of the class definition


  17. class A() {}  

  18. // equivalently:
  19. class A {}

  20. // or even
  21. class A



  22. // Every class C defines a type C
  23. // Each *instance* of a class C, which we call an object,
  24. // is a value of type C

  25. // objects are created with the construct (new _)

  26. new A


  27. val a1 = new A

  28. val a2 = new A

  29. a1 == a2

  30. a1 eq a2


  31. // The body of a class declaration is a block and
  32. // can contain anything allowed in a block
  33. // Any declarations within the body have only local scope in there

  34. class B {
  35.   var x = 1         
  36.   val s = "abc"

  37.   def m(n: Int) = x + n
  38. }

  39. // variables in a class are also called "fields"

  40. // The fields of an instance of class B constitute's
  41. // the object's *internal state*.

  42. // Fields and methods can be accessed using the common
  43. // dot notation

  44. val b = new B

  45. b.x

  46. b.s

  47. b.m(10)

  48. // the value stored in a mutable field can be modified
  49. // with assignments
  50. b.x = 7

  51. b.m(10)

  52. // Whatever expressions are in a class' body they are
  53. // evaluated at object creation time
  54. // The effect of this evaluation is a new object
  55. class B {
  56.   println("Starting creating new object of class B")
  57.   var x = 1
  58.   val s = "abc"

  59.   def m(n: Int) = x + n

  60.   def g = 33  // parameterless method

  61.   println("Done creating new object of class B")
  62. }

  63. new B



  64. /* Operational difference between fields and
  65.    parameterless methods
  66. */

  67. // The value of an object's field is determined at object
  68. // creation time. In contrast, a parameterless method is
  69. // still a method, so its returned value is computed
  70. // anew each time the method is called.

  71. class A {
  72.   var x = 0
  73.   val y = x + 1  // y will be initialized to 1 and stay so
  74.   def f = x + 1  // the value returned by f each time depends
  75.                  // on the current value of x
  76. }

  77. val a = new A

  78. a.x
  79. a.y  // evaluates to 1
  80. a.f  // evaluates to 1

  81. a.x = 4

  82. a.y  // still evaluates to 1
  83. a.f  // evaluates to 5


  84. // A class declaration can have input parameters
  85. class Point(x0:Double, y0:Double) {
  86.   val x = x0
  87.   val y = y0
  88. }

  89. val p = new Point(4.5, 3.9)

  90. p.x

  91. p.y

  92. // input parameters are used only at object creation time

  93. p.x0   // error

  94. // but they can turned into fields as in the example below

  95. class Point(val x:Double, val y:Double) {}

  96. // x, y are both input parameters and (immutable) fields

  97. val p = new Point(6.5, 3.1)

  98. p.x

  99. p.y

  100. // "class Point(val x:Double, val y:Double) {}" is just
  101. // an abbreviation for a declaration of the form
  102. class Point(x0:Double, y0:Double) {
  103.   val x = x0
  104.   val y = y0
  105. }




  106. // Fields and methods are exposed by default: they are "public"
  107. // They can be hidden inside by declaring them as "private"
  108. // private fields and methods are visible only by objects of the same class
  109. class Point(x0:Double, y0:Double) {
  110.   private val x = x0
  111.   private val y = y0

  112.   def coincidesWith (other: Point) =
  113.     (x == other.x) && (y == other.y)
  114.     // other.x and other.y are visible by current point
  115. }



  116. val p1 = new Point(6.5, 3.1)

  117. p1.x  //  error

  118. val p2 = new Point(6.5, 3.1)

  119. p1.coincidesWith(p2)

  120. p1 == p2

  121. // note less verbose alternative notation
  122. p1 coincidesWith p2


  123. // more abbreviations:
  124. class Point(private val x:Double, private val y:Double) {
  125. }
  126. // abbreviates something like
  127. class Point(x0:Double, y0:Double) {
  128.   private val x = x0
  129.   private val y = y0
  130. }



  131. // inside a class method definition the object that receives the calls
  132. // can be referred to by 'this'
  133. class Point(private val x:Double, private val y:Double) {

  134.   def coincidesWith (other:Point) =
  135.     (this.x == other.x) && (y == other.y)
  136.     // 'this.x' is the same as just x

  137.   def sameAs (other:Point) =
  138.     this eq other
  139. }

  140. val p1 = new Point(6.5, 3.1)
  141. val p2 = new Point(6.5, 3.1)

  142. p1 sameAs p2

  143. p1 sameAs p1

  144. val p3 = p1

  145. p1 sameAs p3


  146. // 'this' can be used also to define alternative object constructors

  147. class Point(val x:Double, val y:Double) {

  148.   // new object constructor, taking only one parameter
  149.   def this(x: Double) =
  150.     this(x, x) // call to basic constructor, implicitly defined
  151.                // by parameters (x0:Double, y0:Double) above

  152.   // another constructor, taking no parameters
  153.   def this() =
  154.     this(0.0)  // call to unary constructor above
  155. }

  156. val p1 = new Point(4.1, 5.9)

  157. val p2 = new Point(1.7)

  158. val p3 = new Point

  159. p2.x
  160. p2.y

  161. p3.x
  162. p3.y


  163. // methods called 'apply' can be called with shorthand syntax
  164. class Point(private val x:Double, private val y:Double) {
  165.   
  166.   def apply(i:Int) =
  167.     i match {
  168.       case 0 => x
  169.       case 1 => y
  170.       case _ => throw new IllegalArgumentException
  171.   }
  172. }

  173. val p = new Point(4.6, 9.1)

  174. p.apply(0)
  175. // can be abbreviated as
  176. p(0)


  177. // operator symbols like +, -, ++, *, **, etc. can be used
  178. // as method names in user-defined classes
  179. class Point(private val x:Double, private val y:Double) {
  180.   def +(other: Point) =
  181.     new Point(x + other.x, y + other.y)

  182.   def -(other: Point) =
  183.     new Point(x - other.x, y - other.y)

  184.   def apply(i:Int) =
  185.     i match {
  186.       case 0 => x
  187.       case 1 => y
  188.       case _ => throw new IllegalArgumentException
  189.   }
  190. }

  191. val p1 = new Point(4.0, 9.0)
  192. val p2 = new Point(3.0, 1.0)

  193. val p = p1.+(p2)

  194. p(0)
  195. p(1)

  196. // leaner syntax

  197. p1 + p2

  198. // user-defined binary operators are left-associative by default
  199. p1 - p2 - p2
  200. // same as
  201. (p1 - p2) - p2



  202. // Scala is pervasively object-oriented
  203. // *every value* is an object of some class

  204. // All basic types (Boolean, Int, Double, Unit, ...) are classes
  205. // Their elements are objects with predefined methods

  206. // Basic operators are actually all methods
  207. // E.g.

  208. val x = 4

  209. // as with user defined classes x + 2   is syntactic sugar for

  210. x.+(2)

  211. // i.e. + is a method of class Int that takes an integer
  212. // (the second operand of +) and returns its addition with
  213. // the receiving object (the first operand)

  214. // 3.2 - 1.7   is  syntactic sugar for

  215. 3.2.-(1.7)

  216. // true && false  is syntactic sugar for  

  217. true.&&(false)

  218. // x == 3   is syntactic sugar for

  219. x.==(3)


  220. // Tuples, Lists, Arrays types are also all classes

  221. val l = List(10, 11, 12)
  222. // l is an object
  223. // l ++ l   is syntactic sugar for

  224. l.++(l)


  225. //  9 :: l  is syntactic sugar for

  226. l.::(9)   

  227. // note the opposite order of the arguments
  228. // :: is a List method, not an Int method

  229. // any predefined or user-defined binary operator starting with ':'
  230. // is treated as a method of its *second* argument as above


  231. // l(1)  is syntactic sugar for

  232. l.apply(1)

  233. // head, tail, length are all parameterless methods

  234. l.head

  235. l.tail

  236. l.length


  237. // All tuple types (e.g., (Int, String) ) are classes
  238. val p = (100, "abc")

  239. // _1 and _2 are methods of the (Int, String) class

  240. p._1

  241. p._2
复制代码

7
ReneeBK 发表于 2016-4-9 09:38:46
  1. Scala Notes

  2. Scala is a multiparadigm language that compiles to Java bytecodes. We will be examining the way that Scala combines the object-oriented features of Java with functional constructs.
  3. These notes were heavily influenced by the lecture slides developed by Cay Horstmann who taught the functional parts of his fall 2008 Progamming Languages course using Scala. If you like what you see, you can explore Cay's course materials yourself.

  4. The main web page for Scala is at http://www.scala-lang.org/. You can download Scala from that site.

  5. It's hard to predict what programming languages will end up being influential, but there is very good buzz around Scala. Read, for example, an interview with Twitter developers talking about their choice of Scala over Ruby for certain parts of their system.

  6. I pointed out that Scala has many things in common with ML and Scheme:

  7. It has a Read-Eval-Print-Loop interpreter that allows you to type expressions and see what they evaluate to
  8. It has basic types for storing numbers (Int, Double), strings (String), boolean values (Boolean), and characters (Char)
  9. It uses the keyword "val" to introduce an immutable binding for an identifier (same as in ML) and uses the keyword "var" to introduce a mutable variable binding (we didn't explore this much because we were looking at the more functional aspects of the language).
  10. It has anonymous functions with a syntax similar to that used in ML. For example:
  11.       val f = (x : Double) => x * x
  12.       val compare = (s1 : String, s2 : String) => s1.length() > s2.length()
  13.       
  14. Everything is an object. It has a type called "Any" that is like Java's Object type. It is the superclass of all classes.
  15. It has an if/then/else construct similar to ML but with required parentheses (as in Java) and Java style equality comparisons (==, !=) and without the keyword "then" and with a type that matches the lowest common ancestor in the type hierarchy:
  16.       if (2 < 3) 1 else 4
  17.       if (2 + 2 == 4) 1 else "hello"
  18.       if (2 + 2 != 4) 1 else "hello"
  19.       
  20. You define functions in a very similar manner to ML but using the keyword "def" instead of the keyword "fun":
  21.       def f(n : Int) = 2 * n
  22.       def fact(n : Int) : Int = if (n == 0) 1 else n * fact(n - 1)
  23.       def fact(n : BigInt) : BigInt = if (n == 0) 1 else n * fact(n - 1)
  24.       
  25. Scala has a limited ability to infer types. For example, you normally don't have to tell Scala the types of val or var bindings. It can infer the return types of nonrecursive functions, but not of recursive functions (that's because it encounters a call on the recursive function before it's had a chance to determine its type).
  26. There is a List type that is similar to ML's list type. The empty list is Nil and you can use the :: operator to construct a list. The list type will be the lowest common ancestor of the types of values inserted into the list.
  27.       Nil
  28.       2 :: Nil
  29.       2.8 :: 2 :: Nil
  30.       "hello" :: 2.8 :: 2 :: Nil
  31.       
  32. You can also enumerate the values:
  33.       List("hello", 2.8, 2)
  34.       
  35. List objects have methods called head and tail, although you call them using the object dot notation without parentheses (list.head, list.tail). As a result, you can write recursive functions that are similar to ML functions:
  36.       def stutter(lst : List[Any]) : List[Any] =
  37.           if (lst.isEmpty) Nil else
  38.           lst.head :: lst.head :: stutter(lst.tail)
  39.       
  40. Note: can't put else on the next line because there is a simple form of if (like Java's if without an else) and line breaks are meaningful.
  41. The List class has many higher order functions built in:
  42.       val lst = List(1, 3, 5, 19, 42, 7, 0, -8, 13, 9, 8, 4, 17, 18)
  43.       lst.lst.map((x : Int) => 2 * x)
  44.       lst.filter((x : Int) => x % 2 == 0)
  45.       lst.reduceLeft((x : Int, y : Int) => x + y)
  46.       lst.sort((x : Int, y : Int) => x > y)
  47.       (0 /: lst) {(x, y) => x + y}
  48.       lst.partition((x : Int) => x > 13)
  49.       
  50. Quicksort can now be written even more concisely (the ::: operator is for list append):
  51.       def quicksort(lst : List[Int]) : List[Int] =
  52.           if (lst.length <= 1) lst else {
  53.               val (a, b) = lst.tail.partition((x : Int) => x <= lst.head)
  54.               quicksort(a) ::: (lst.head :: quicksort(b))
  55.           }
  56.       
  57. As in Ruby and Python, you can access individual elements of a list given an index or you can access a "slice":
  58.       val lst = List(1, 3, 5, 19, 42, 7, 0, -8, 13, 9, 8, 4, 17, 18)
  59.       lst(3)
  60.       lst.slice(2, 8)
  61.       
  62. Using slices, we can write mergesort fairly concisely:

  63.       def merge(lst1 : List[Int], lst2 : List[Int]) : List[Int] =
  64.           if (lst1.isEmpty || lst2.isEmpty) lst1 ::: lst2 else
  65.           if (lst1.head <= lst2.head) lst1.head::merge(lst1.tail, lst2) else
  66.               lst2.head::merge(lst1, lst2.tail)
  67.       
  68.       def msort(lst : List[Int]) : List[Int] =
  69.           if (lst.length <= 1) lst else {
  70.               val mid = lst.length / 2
  71.               merge(msort(lst.slice(0, mid)), msort(lst.slice(mid, lst.length)))
  72.           }
  73.       
  74. As in Ruby and Python, there is a Range type and a foreach construct:
  75.       1 to 10
  76.       for (n <- 1 to 10) println(n)
  77.       ("blastoff" /: (1 to 10)) {(x, y) => y + ", " + x}
  78.       
  79. Scala has tuples that are similar to what we saw in ML:
  80.       (2, 3)
  81.       (3, "hello", 14.5)
  82.       val (x, y, z) = (3, "hello", 14.5)
  83.       
  84. Class definitions can be much simpler than in Java. For example, this declaration:
  85.       class Data(val n : Int, var x : Double)
  86.       
  87. Introduces the class, a constructor that takes two arguments, accessor methods for n and x (called n and x), and a mutator for x called x_$eq.
  88. Scala, like Java, has an ability to use reflection to ask an object about itself (its class, its methods, etc). Unlike Java, the syntax to access that information is a little more convenient, as in:
  89.       class Data(val n : Int, var x : Double)
  90.       val a = new Data(3, 14.5)
  91.       a.getClass
  92.       for (m <- a.getClass.getMethods) println(m)
  93.       
  94. And much more that we didn't have time to look at including: closures, option type, overloaded operators, continuations, curried functions and partially instantiated functions, Map and Set collections, support for concurrency, and some limited mixin and pattern matching capabilities.
  95. The complete log of the Scala session from the lecture is available here.
  96. Stuart Reges
  97. Last modified: Fri Nov 27 18:08:01 PST 2009
复制代码

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群
GMT+8, 2026-1-3 00:18