Skip to content

Allow default values for closure parameters #11318

Closed

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]
 1 │ let 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
╭───┬───╮
│ 0 │ 0 │
│ 1 │ 1 │
│ 2 │ 1 │
│ 3 │ 2 │
│ 4 │ 3 │
╰───┴───╯

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.

Activity

  1. added
    category:enhancement
    status:needs-triage
    on Dec 13, 2023
  2. amtoine commented on Dec 13, 2023

    @amtoine
    Member

    i think it would be great, kinda related to optional parameters i talk about in #11287 👍

  3. added
    A:syntax
    on Dec 13, 2023
  4. NotTheDr01ds commented on Dec 14, 2023

    @NotTheDr01ds
    ContributorAuthor

    @amtoine Great point - I didn't think about trying the optional/? syntax. Ultimately the same scenario there.

  5. added this to the v0.92.0 milestone on Mar 11, 2024
  6. added a commit that references this issue on Mar 11, 2024
    5596190
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A:syntaxcategory:enhancementstatus:needs-triage

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions