Skip to content

Feature request: lazy default #14160

@aionescu

Description

@aionescu

Related problem

Sometimes when using default, the "default" value is expensive to compute (or produces side-effects), so I'd like it to be computed lazily, only if the input is actually null.

Describe the solution you'd like

I'd like to be able to pass a closure to default instead of a value, and the closure to get run only if the input is null.

To prevent confusing behavior when the value being defaulted is itself a closure, I think this would work best as a flag on default, like --closure(-c) or --lazy(-l).

For example:

> 2 | default -c { print Hi; 3 }
2

> null | default -c { print Hi; 3 }
Hi
3

> { x: 2, y: 4 } | default -c { print Hi; 3 } y
{ x: 2, y: 4 }

> { x: 2 } | default -c { print Hi; 3 } y
Hi
{ x: 2, y: 3 }

Contrast this with the output of regular default:

> 2 | default (print Hi; 3)
Hi
2

Describe alternatives you've considered

Currently, to get this behavior, you need to resort to a clunky if-expression of the form:

if $thing != null { $thing } else { $expensive_computation }

This is especially annoying if $thing is itself a complex expression, as you have to bind it to a variable to avoid duplicating it.

Additional context and details

This feature is very similar to Option::unwrap_or_else from the Rust stdlib.

I'm planning to write the PR for this myself, but wanted to submit the feature request first to get feedback on the usage and API.

Metadata

Metadata

Assignees

No one assigned

    Labels

    category:enhancementNew feature or requestsemanticsPlaces where we should define/clarify nushell's semantics

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions