Advertisement
Guest User

Untitled

a guest
Feb 7th, 2016
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. import scala.collection.mutable.ListBuffer
  2.  
  3. object Max {
  4.  
  5. // tail recursive calculation
  6. def maxTail(list: List[Int]): Int = {
  7.  
  8. // local function
  9. def maxTailLocal(list: List[Int], max: Int): Int = {
  10.  
  11. if (list.isEmpty) {
  12. max
  13. } else if (list.head > max)
  14. maxTailLocal(list.tail, list.head)
  15. else {
  16. maxTailLocal(list.tail, max)
  17. }
  18. }
  19.  
  20. //local function call
  21. maxTailLocal(list, Int.MinValue)
  22. }
  23.  
  24. // pattern matching calculation
  25. def maxPattern(list: List[Int]): Int = {
  26.  
  27. //local function
  28. def maxPatternLocal(list: List[Int], max: Int): Int = list match {
  29. case List() => max
  30. case head :: tail => if (head > max)
  31. maxPatternLocal(tail, head)
  32. else
  33. maxPatternLocal(tail, max)
  34. }
  35.  
  36. //local function call
  37. maxPatternLocal(list, Int.MinValue)
  38. }
  39.  
  40.  
  41. def main(args: Array[String]) {
  42.  
  43. if(args.length < 1){
  44. Console.err.println("You have to pass a list of integer arguments!")
  45. return
  46. }
  47.  
  48. val listBuffer = new ListBuffer[Int]
  49.  
  50. print("List: ")
  51. for (arg <- args) {
  52. listBuffer += arg.toInt
  53. print(arg + " ")
  54. }
  55. println()
  56.  
  57. println("Max value tail recursion: " + maxTail(listBuffer.toList))
  58. println("Max value pattern matching: " + maxPattern(listBuffer.toList))
  59.  
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement