Adding with_trampoline function

This commit is contained in:
Sławomir Śledź 2018-02-14 01:19:43 +01:00
parent cb9eff8b81
commit b5a3c9eea0
2 changed files with 63 additions and 2 deletions

View file

@ -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))' 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) \ 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))' | 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

View file

@ -242,7 +242,7 @@ zip() {
done done
} }
function curry() { curry() {
exportfun=$1; shift exportfun=$1; shift
fun=$1; shift fun=$1; shift
params=$* params=$*
@ -253,3 +253,25 @@ function curry() {
eval $cmd 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
}