Exercise 9.2.1 Design a tail-recursive version of length.
Ah, tail recursion again. Re-iterating that in a tail recursion, the last line of the function has to be a pure call to itself. To achieve this, an extra parameter needs to be passed to the function that keeps track of some relevant state.
We are getting good at this now, arent we?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object TailRecursiveListLength { | |
def trlength(l: List[Int], counter: Int): Int = l match { | |
case Nil => counter | |
case x :: xs => trlength(xs, counter + 1) | |
} | |
def main(args: Array[String]) { | |
println("Length of list () is: " + trlength(List(), 0)) | |
println("Length of list (1,6,2,5,8,93) is: " + trlength(List(1,6,2,5,8,93), 0)) | |
} | |
} |
No comments:
Post a Comment