Today I Learned (May 23, 2024)

NuShell has closure’s and allows higher order function patterns

NuShell supports first-class functions (closures, to be more precise). This, conveniently, allows higher order function patterns like assigning functions to variables, passing them to other functions and returning them from functions.

We may, for example, define a greet function and bind it to a variable.

let greet = { |name: string| print $"Hello, ($name)!" }

In Nushell, functions may be run with the do command. So we write

$ do $greet "Anna"
Hello, Anna!

to greet Anna.

Now, if we want to define a higher order function apply that takes a function and calls it, we may write this as follows:

def apply [f: closure, x] { do $f $x }

:bulb: Note that the type of closures is closure, *duh*. :)

We may call apply like so:

$ apply $greet "Anna"
Hello, Anna!

:link: ( Types of Data / Closures

:link: ( Commands / DO