Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scala.collection.mutable.ListBuffer
- object Max {
- // tail recursive calculation
- def maxTail(list: List[Int]): Int = {
- // local function
- def maxTailLocal(list: List[Int], max: Int): Int = {
- if (list.isEmpty) {
- max
- } else if (list.head > max)
- maxTailLocal(list.tail, list.head)
- else {
- maxTailLocal(list.tail, max)
- }
- }
- //local function call
- maxTailLocal(list, Int.MinValue)
- }
- // pattern matching calculation
- def maxPattern(list: List[Int]): Int = {
- //local function
- def maxPatternLocal(list: List[Int], max: Int): Int = list match {
- case List() => max
- case head :: tail => if (head > max)
- maxPatternLocal(tail, head)
- else
- maxPatternLocal(tail, max)
- }
- //local function call
- maxPatternLocal(list, Int.MinValue)
- }
- def main(args: Array[String]) {
- if(args.length < 1){
- Console.err.println("You have to pass a list of integer arguments!")
- return
- }
- val listBuffer = new ListBuffer[Int]
- print("List: ")
- for (arg <- args) {
- listBuffer += arg.toInt
- print(arg + " ")
- }
- println()
- println("Max value tail recursion: " + maxTail(listBuffer.toList))
- println("Max value pattern matching: " + maxPattern(listBuffer.toList))
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement