Home > naming > How to name nested function?

How to name nested function?

September 10Hits:1

When you have a function that wraps another one in Scala. What do you call the nested function?

I found this :

def factorial(i: Int): Int = {    def fact(i: Int, accumulator: Int): Int = {      if (i <= 1)         accumulator      else         fact(i - 1, i * accumulator)   }    fact(i, 1)  } 

I usually use just do because it is shorter, generic, and explicit. But is there a better way or a naming convention for nested functions?

def myFunction() = {    def do(i: Int) = {     ...   }   do(1)  } 


There is no need for a convention. Local functions are not exposed to the rest of the code, so nothing anybody else writes will care about it. I say choose something that makes sense in context, rather than worry about a convention which may work well in one place, not in another.

Here is a tail-recursive fibonacci implementation:

def fib (n: Long): Long = {
  def loop(current: Long, next: => Long, iteration: Long): Long = {
    if (n == iteration)
      loop(next, current + next, iteration + 1)
  loop(0, 1, 0)

I could have called it fibloop, but I don't really think that adds anything. It's not accessible anywhere else, so why bother "namespacing" it? Perhaps calling it forwardloop might be clearer, but not fibloop. If anything, calling it loop emphasises that it is local.

If your methods/functions are so long that you've forgotten where a helper/local function was defined by the time you see it again, I could see the need for a naming convention (although if the function is named so as to make its purpose clear, how often will it matter?). Personally, I try to avoid writing anything that verbose, but if you do, then I suggest you save special conventions for those methods where this actually becomes a problem. Even then, I bet a well chosen name will be more helpful than any number of underscores.

If a method is succinct enough, (and the local function also simple) I confess I sometimes use a function literal just to avoid having to worry about the name.

Now, you might counter that prefixing local functions with an underscore definitively avoids the possibility of shadowing an external function. To which I would respond by asking what happens if you have a local function inside another local function? Use two underscores? If you re-organise your code, how much search-and-replace are you prepared to do, to chase after this problem you created for yourself?

A convention I've seen in some other languages is to use a leading or trailing underscore for a private, temporary named function that exists purely as an implementation detail:

def factorial(i : Int): Int = {
  def _factorial(i : Int, acc : Int): Int = {

I don't believe there's an official standard in this case. Just calling it fact or factorialImplementation or something should be fine.

Speaking of factorial, I assume this is being done for the sake of learning right? Because there are a number of shorter and potentially easier-to-maintain ways to get the same results. I like the implementation that uses reduceLeft (or foldl1 if you come from Haskell-land):


Tags:naming, scala

Related Articles

  • Should I nest functions in languages that allow me to do that or should I rather avoid it?February 29

    In JavaScript, PL/SQL and some other languages, functions can be nested, i.e. declared within another function. This could be used to break a large function into smaller pieces, but keep those pieces within the context of the larger function. functio

  • var that = this; Keeping a class in scope of nested functionsJuly 5

    I've been using this syntax alot recently to keep my class in scope of nested functions. It seems to work well in small to moderately sized class but I'm starting to wonder how efficient it actually is and if there is a better way to handle this. Any

  • Comparing the last output of a nested function with all the previous ones

    Comparing the last output of a nested function with all the previous onesJuly 18

    my main question is how I can compare the last output of a nested function with all the previous ones and stop iterating when I find a repeating value. (I have 2 other questions but I think they are so simple that they do not deserve a separate topic

  • Nesting Functions within FunctionsAugust 6

    I'm looking for an efficient way to group a series of separate but related functions for a child theme I'm designing using theThematic Theme Framework. Thematic does a great job of providing plenty of action hooks and filters for child theme developm

  • Precise Timing for nested functions, how to?

    Precise Timing for nested functions, how to? November 25

    Possible Duplicate: Profiling from Mathematica How can I easily get fractions of timing for each nested function? Consider a nested call like this: Total[DigitCount[Mod[(2^10000) + 1, Prime[100]]]] I don't want to assign each parameter to a variable

  • Break out of nested functions in a shellMarch 6

    If I have a series of nested functions, how can I break out of all of them from the innermost function? EDIT: Busy looking into the builtin 'trap'... --------------Solutions------------- A rather ugly but easy way to achieve this would be defining ST

  • Using nested functions in XSLT (function inside function)July 29

    I have the following two functions in XSLT 1.0 ShortenDetail RemoveHTML I am trying to first clean "Detail" column using RemoveHTML function and then I want to shorten it using ShortenDetail function. This is how I am doing it but it is not work

  • How to name nested function? September 10

    When you have a function that wraps another one in Scala. What do you call the nested function? I found this : def factorial(i: Int): Int = { def fact(i: Int, accumulator: Int): Int = { if (i <= 1) accumulator else fact(i - 1, i * accumulator) } fact

  • Why does a working standalone nested function/script not work inside a larger script? November 4

    This question already has an answer here: Command substitution in for loop not working 3 answers The following (nested) function/s function hpf_matrix { # Positional Parameters Matrix_Dimension="${1}" Center_Cell_Value="${2}" # Define

  • Edate cannot have nested function call?

    Edate cannot have nested function call?December 8

    Why is it that this function does not display a date in Google Spreadsheets? =edate(today(),6) I am trying to display the date that is 6 months from today. Instead, the cell only shows a value like this: 41,797. It seems that I cannot embed the funct

  • Creating nested functions for purely aesthetic reasons?April 11

    I've always wondered what other programmers think about the idea of creating pure aesthetic functions. Say I have a function that processes a chunk of data: Function ProcessBigData. Say I need several process steps, only valid for that data: Step1, S

  • what does it mean when a nested function isn't assigned to a var?July 4

    I'm referencing this link about closures: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work This is specifically about javascript. In the second answer with 956 votes, The author returns the nested function "sayAlert" aft

  • Function has two sets of arguments, the latter of which calls a nested function? October 1

    The function foo, has a nested function; bar. Calling foo with a second set of arguments feeds them into bar if bar is returned at the end of foo. How does this work and what is it called? Are there any uses for it over simply having a single set of

  • What is the shortest way to switch between heads of nested functions

    What is the shortest way to switch between heads of nested functionsNovember 5

    consider this example: f[g[x]] what is the shortest way to switch between heads of nested functions to produce. g[f[x]] --------------Solutions------------- For your particular example, Thread[f[g[x]], g] Generally, we can think of Thread as of a fun

  • What is the maximum number of nested functions in PIC16F628A?December 5

    What is the maximum number of nested functions in PIC16F628A? ex. [NEW CODE, should be more explanatory] int main(){ function1(); } void function1(){ function2(); } void function2(){ function3(); } void function3(){ function4(); } // And so on void f

  • Nested functions; allow or not? July 13

    Having programmed a whole lot in python, using nested functions is a good way to not clutter the namespace with small helper functions that are only used once. Now I'm programming in go, and upon writing some code that I immediately wanted to refacto

  • The largest odd number (follow-up code using nested functions)September 28

    Ask user to input 10 integers and then print the largest odd number that was entered. If no odd number was entered, print a message to that effect. This is my follow-up code on feedback from Find the largest odd number (follow-up code) This time I'm

  • Nested function with an increasing argument

    Nested function with an increasing argumentDecember 5

    If, for example, I have a nesting function like Nest[1 + x^n (#) &, 1, 3] it gives the result 1 + x^n (1 + x^n (1 + x^n)) I would need the n to increase by one with every step, just like in a sum or product function, so that the result would be 1 + x

  • How well does v8 optimise nested functions?January 15

    Sometimes I see code like: var doSomething = function(object){ var results = [] var doSomethingElse = function(object){ ... } results.push(doSomethingElse(...)) return results } Organised this way because doSomethingElse only has meaning within doSom

  • Order of execution of nested functions in dplyr pipeJanuary 15

    When I use nested function in a piping step, the order of execution seems unintuitive. df <- data.frame(a = c(1,NA,2), b = c(NA, NA, 1)) df %>% is.na %>% colSums # Produce correct count of missing values df %>% colSums(is.na(.)) # Produce NA C

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.557 s.