'tail recursion count, split & get the prefix of a list functions

Language: Scala

I'm working on some tail recursion questions in Scala.

(GOAL) A function that counts the number of ones in a list. The function takes a list of ints and counts how many ones are in the list

Restrictions include:

  • No loops (for-loops, while loops etc..), and No mutables (var).
  • Must be tail recursive

What I have done:

import scala.annotation.tailrec

@tailrec
def countOnes(lst: List[Int], acc: Int = 0): Int = {
    
    if (lst.contains(1)){
        
         lst.count(_ == 1)
    }
    else {
        acc
    }
    countOnes(lst, acc)
}


Solution 1:[1]

One of the common approaches to solving such tasks is to use pattern matching. For example first one can look like:

@tailrec
def countOnes(lst: List[Int], acc: Int = 0): Int = lst match {
  case 1 :: tail => countOnes(tail, acc + 1) // if lists starts with one - increment acc and process the rest of it
  case _ :: tail => countOnes(tail, acc) // otherwise process the rest
  case Nil       => acc, // for empty list - return accumulator
} 

The same approach can be applied to other 2.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1