mrueg
mrueg

Reputation: 8225

Naming scheme for helper functions in Scala

In Haskell, when I need a quick worker function or helper value, I usually use prime (') that is widely used in mathematics. For instance, if I were to write a reverse function and needed a tail-recursive worker, I would name it reverse'.

In Scala, function names can't contain a '. Is there any commonly accepted naming scheme for helper functions and values in Scala?

Upvotes: 7

Views: 1416

Answers (2)

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 59994

If I remember well from Martin Odersky's programming course I took in 2004, I think he used the 0 suffix for helper functions — defined within the body of the main function.

def reverse(...) = {
  def reverse0(...) = {
    // ...
  }
  reverse0(...)
}

Upvotes: 7

Kim Stebel
Kim Stebel

Reputation: 42047

Why don't you declare the method inside of the method that uses it? Then you can just call it "helper" or whatever you like without having to worry about name conflicts.

scala> def reverse[A](l:List[A]) = {
     |   def helper(acc:List[A],rest:List[A]):List[A] = rest match {
     |     case Nil => acc
     |     case x::xs => helper(x::acc, xs)
     |   }
     |   helper(Nil, l)
     | }
reverse: [A](l: List[A])List[A]

scala> reverse(1::2::3::Nil)
res0: List[Int] = List(3, 2, 1)

Upvotes: 13

Related Questions