Browse Source

Fixed some behavior error of mapl and foldl

master
parent
commit
b99ccff043
  1. 28
      src/fold
  2. 20
      src/map
  3. 6
      test/test

28
src/fold

@ -11,7 +11,7 @@ fold () {
return 1
} else {
typeset f="\$($1 \$acc \$1)"; shift
foldl "$f" "$@"
foldlp "$f" "$@"
}
}
@ -26,7 +26,7 @@ foldl () {
local body=$1
local acc=$2
shift 2
for x; acc=$(fold_ $x $acc $body)
for x; acc=$(folde_ $x $acc $body)
print -- $acc
return 0
}
@ -34,7 +34,24 @@ foldl () {
folda () {
typeset f="\$[ $1 ]"; shift
foldl "$f" "$@"
foldlp "$f" "$@"
}
foldlp () {
if (($#<2)) {
{
print -- 'Warning, l is not for left! Its for lambda style expression!'
print -- 'Though this is left fold still :)'
} >&2
return 1
} else {
local body=$1
local acc=$2
shift 2
for x; acc=$(fold_ $x $acc $body)
print -- $acc
return 0
}
}
fold_ () {
@ -42,3 +59,8 @@ fold_ () {
local body=$3
print "${(e)body}"
}
folde_ () {
local acc=$2
local body=$3
eval "${(e)body}"
}

20
src/map

@ -31,9 +31,13 @@ mapl () {
typeset f="$1"; shift
typeset x
typeset result=0
for x; map_ "$x" "$f" || result=$?
for x; mapl_ "$x" "$f" || result=$?
return $result
}
mapl_ () {
eval "${(e)2}"
}
mapa () {
(($#<1)) && {
@ -48,10 +52,18 @@ mapa () {
return 1
}
typeset f="\$[ $1 ]"; shift
mapl "$f" "$@"
mapa__ "$f" "$@"
}
map_ () {
print -- "${(e)2}"
mapa__ () {
(($#<1)) && return 1
typeset f="$1"; shift
typeset x
typeset result=0
for x; mapa_ "$x" "$f" || result=$?
return $result
}
mapa_ () {
print -- "${(e)2}"
}

6
test/test

@ -37,15 +37,15 @@ addition () { echo $(($1 + $2)) }
ignore_acc () { echo $2 }
TEST "map can (+1) numbers " "map plus_one {0..5} " "1 2 3 4 5 6"
TEST "mapl echo append " "mapl '\$1 day' good bad " "good day bad day"
TEST "mapl echo append " "mapl 'echo \$1 day' good bad " "good day bad day"
TEST "mapa can (+1) " "mapa '\$1 + 5' {1..3} " "6 7 8"
TEST "filter can remove odd numbers " "filter divisible_by_two {0..4} " "0 2 4"
TEST "filterl can grep out words " "filterl 'echo \$1 | grep a --silent' ab bc ac " "ab ac"
TEST "filtera can remove odd numbers " "filtera '\$1%2 == 0' {0..4} " "0 2 4"
TEST "fold can sum numbers " "fold addition 0 {1..5} " "15"
TEST "fold is not commutative " "fold ignore_acc a b c d " "d"
TEST "foldl palin " "foldl '\$1\$acc\$1' MIDDLE = + = = " "==+=MIDDLE=+=="
TEST "foldl palin2 " "foldl '\$1\$2\$1' MIDDLE = + = = " "==+=MIDDLE=+=="
TEST "foldl palin " "foldl 'echo \$1\$acc\$1' MIDDLE - O o . " ".oO-MIDDLE-Oo."
TEST "foldl palin2 " "foldl 'echo \$1\$2\$1' MIDDLE - O o . " ".oO-MIDDLE-Oo."
TEST "folda can sum numbers " "folda '\$1+\$2' 0 {1..5} " "15"
TEST "each can only append " "each 'echo young' boy girl " "young boy young girl"
TEST "eachl can prepend " "eachl 'echo \$1 day' good bad " "good day bad day"

Loading…
Cancel
Save