Field Note

Nushell `closure`s and higher order function patterns

nushell closure functional-programming
Posted on Thursday, May the 23rd 2024
1 min read

Nushell has 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 }
Note that the type of closures is simply closure. :)

We may call apply like so:

$ apply $greet "Anna"
Hello, Anna!
friedrichkurz.me

© 2025 Friedrich Kurz

Privacy Policy