1
Fork 0
mirror of https://github.com/RGBCube/nu_scripts synced 2025-08-02 07:07:46 +00:00

Adds Modules/recursion : Examples of Fun with Recursive functions in Nu (#717)

This directory contains some examples of running recursive algorithms in
Nu. It also has the module : tramp which implements the Trampoline
pattern to overcome the lack of Tail Call Optimization (TCO) avoiding
unlimited stack growth.

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
This commit is contained in:
Ed Howland 2023-12-27 14:04:52 -05:00 committed by GitHub
parent 258670c957
commit b2fb2b441b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 497 additions and 0 deletions

View file

@ -0,0 +1,36 @@
# merge 2 sorted lists
# Merge 2 sorted lists
def merge-2 [l: list, r: list] -> list {
mut ol = []
mut lprime = $l; mut rprime = $r
let mx = ($l | length) + ($r | length)
#print -e $"l: ($l), r: ($r)"
while ($ol | length) < $mx {
if ($lprime | is-empty) or ($rprime | is-empty) { break }
if $lprime.0 <= $rprime.0 {
$ol = ($ol | append $lprime.0)
$lprime = ($lprime | skip)
} else {
$ol = ($ol | append $rprime.0)
$rprime = ($rprime | skip)
}
}
$ol | append $lprime | append $rprime
}
# Merge sort a list
# This version is non tail call optimized and might blow the stack for
# large lists.
def sort-nontail [x: list] -> list {
let $n = ($x | length)
let n_2: int = $n // 2
if $n <= 1 {
$x
} else {
merge-2 (sort-nontail ($x | first $n_2)) (sort-nontail ($x | skip $n_2))
}
}