Skip to content

Allow default values for closure parameters #11318

@NotTheDr01ds

Description

@NotTheDr01ds

Related problem

When defining a custom command, we can obviously specify default parameters, e.g.:

def greet [ name="World", greeting="Hello" ] {
    $"($greeting), ($name)"
}

> greet
Hello, World

> greet Dave
Hello, Dave

... etc.

However, this doesn't work for the equivalent closure:

let greet = { 
    |name="World", greeting="Hello"|
    $"($greeting), ($name)"
}

> do $greet
Error: nu::shell::variable_not_found

  × Variable not found
   ╭─[entry #5:1:1]
 1let greet = { |name="World", greeting="Hello"| $"($greeting), ($name)"}
   ·                                                   ────┬────
   ·                                                       ╰── variable not found
   ╰────

> do $greet Dave Bonjour
Bonjour, Dave

Describe the solution you'd like

Allow do $greet to work with the default parameter values.

Describe alternatives you've considered

No response

Additional context and details

My ultimate goal is using these with generate in a more syntactically pleasing manner. E.g., using a modified example from the help:

> let fibGenerator = {
      |fib = [ 0,1 ]|
      {
          out: $fib.0,
          next: [$fib.1, ($fib.0 + $fib.1)]
      }
  }

> generate $fibGenerator | first 5
╭───┬───╮
│ 00 │
│ 11 │
│ 21 │
│ 32 │
│ 43 │
╰───┴───╯

It seems to me that most generators are going to have a default value anyway (e.g., page = 1 for a paging API call). It seems more readable to have it as part of the generator definition than the invocation. E.g., the way it is today:

generate [ 0, 1 ] $fibGenerator | first 5

Of course, having this work with generators will require additional work, but allowing closure parameters to use default values (this issue) is a pre-req for that.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A:syntaxChanges to the grammar or syntax beyond parser bugfixescategory:enhancementNew feature or requeststatus:needs-triageAn issue that hasn't had any proper look

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions