diff --git a/examples/example.sh b/examples/example.sh index 10e8b0e..80cb792 100755 --- a/examples/example.sh +++ b/examples/example.sh @@ -117,4 +117,43 @@ echo 0 | cat - <(curl -s https://raw.githubusercontent.com/ssledz/bash-fun/v1.1. map lambda a . 'list $a' | foldl lambda acc el . 'echo $(($acc + 1))' echo 0 | cat - <(curl -s curl -s https://raw.githubusercontent.com/ssledz/bash-fun/v1.1.1/src/fun.sh) \ - | foldl lambda acc el . 'echo $(($acc + 1))' \ No newline at end of file + | foldl lambda acc el . 'echo $(($acc + 1))' + + +factorial() { + fact_iter() { + local product=$1 + local counter=$2 + local max_count=$3 + if [[ $counter -gt $max_count ]]; then + echo $product + else + fact_iter $(echo $counter\*$product | bc) $(($counter + 1)) $max_count + fi + } + + fact_iter 1 1 $1 +} + +factorial_trampoline() { + fact_iter() { + local product=$1 + local counter=$2 + local max_count=$3 + if [[ $counter -gt $max_count ]]; then + res $product + else + call fact_iter $(echo $counter\*$product | bc) $(($counter + 1)) $max_count + fi + } + + with_trampoline fact_iter 1 1 $1 +} + +echo Factorial test + +time factorial 30 +time factorial_trampoline 30 + +time factorial 60 +time factorial_trampoline 60 \ No newline at end of file diff --git a/src/fun.sh b/src/fun.sh index e3d0ba5..07da0a7 100755 --- a/src/fun.sh +++ b/src/fun.sh @@ -242,7 +242,7 @@ zip() { done } -function curry() { +curry() { exportfun=$1; shift fun=$1; shift params=$* @@ -253,3 +253,25 @@ function curry() { eval $cmd } +with_trampoline() { + local f=$1; shift + local args=$@ + while [[ $f != 'None' ]]; do + ret=$($f $args) +# echo $ret + f=$(tupl $ret) + args=$(echo $ret | tupx 2- | tr ',' ' ') + done + echo $args +} + +res() { + local value=$1 + tup "None" $value +} + +call() { + local f=$1; shift + local args=$@ + tup $f $args +}