7

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?

mrueg
  • 8,185
  • 4
  • 44
  • 66

2 Answers2

13

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)
Kim Stebel
  • 41,826
  • 12
  • 125
  • 142
  • 2
    In addition to that you can still just call it reverse, since the signatures vary. – agilesteel Sep 12 '11 at 12:12
  • 1
    I prefer the name `loop` for inner methods when its sense is looping. – kiritsuku Sep 12 '11 at 12:58
  • I use `loop`, too. If the inner method has a kind of accumulator value, I use the suffix `Acc`. A typical Haskell name for unspecific inner methods is `go`. – Landei Sep 12 '11 at 13:37
  • 2
    @agilesteel: the problem with calling it reverse with a different signature is that if there are two overloads for a given name then type inference ceases to flow from the call to its arguments, which means you'll usually need more type annotations. – Edward Kmett Sep 12 '11 at 16:25
  • In case of performance concerns, see [here](http://stackoverflow.com/questions/2482326/the-cost-of-nested-methods). – Raphael Sep 12 '11 at 17:44
  • @Edward Kmett: I agree, but in this case the inner reverse method is recursive, so the return type has to be explicitly mentioned anyway. – agilesteel Sep 12 '11 at 17:57
  • 1
    You could also follow the [Haskell convention to name your helper function "go"](http://stackoverflow.com/questions/5844653/haskell-why-the-convention-to-name-a-helper-function-go) ;) – Dan Burton Sep 12 '11 at 22:24
7

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(...)
}
Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234