Skip to content

Commit 02f5e4c

Browse files
authored
Merge pull request #24 from barbasa/master
SCALA-44 Tail recursion in Scala
2 parents 1995dd5 + f1eee33 commit 02f5e4c

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.baeldung.scala.tailrec
2+
import scala.annotation.tailrec
3+
4+
object StringLength {
5+
6+
def recursiveLength(list: List[String]): Long = list match {
7+
case Nil => 0
8+
case head :: tail => 1 + recursiveLength(tail)
9+
}
10+
11+
def recursiveLengthVerbose(list: List[String]): Long = list match {
12+
case Nil => 0
13+
case head :: tail => {
14+
val accumulator = recursiveLengthVerbose(tail)
15+
1 + accumulator
16+
}
17+
}
18+
19+
@tailrec
20+
def tailRecursiveLength(list: List[String], accumulator: Long): Long = list match {
21+
case Nil => accumulator
22+
case head :: tail => tailRecursiveLength(tail, accumulator + 1)
23+
}
24+
}

0 commit comments

Comments
 (0)