Skip to content

Instantly share code, notes, and snippets.

@sug0
Created February 12, 2018 23:37
Show Gist options
  • Save sug0/f335289b22efb03c78ec7d381ad388fc to your computer and use it in GitHub Desktop.
Save sug0/f335289b22efb03c78ec7d381ad388fc to your computer and use it in GitHub Desktop.
Toy functional tools for the shell
#!/bin/sh
lambda() {
if [ ! $__lambda ]; then
__lambda=`printf "lambda_%s" $(date +%s)`
eval " \
$__lambda() { \
$1; \
};"
fi
$__lambda "$2"
}
__lambda_cleanup() {
if [ $__lambda ]; then
unset $__lambda
unset __lambda
fi
}
map() {
for x in $2; do
eval $1 $x
done
__lambda_cleanup
}
filter() {
for x in $2; do
if eval $1 $x; then
echo $x
fi
done
__lambda_cleanup
}
reduce() {
for x in $2; do
if [ $__has_one ]; then
z=`eval $1 $z $x`
else
z=$x
__has_one=1
fi
done
echo $z
unset __has_one
__lambda_cleanup
}
succ() {
bc << EOF
$1 + 1
EOF
}
pred() {
bc << EOF
$1 - 1
EOF
}
division() {
bc << EOF
scale=12
$1 / $2
EOF
}
##########################################################
echo reduce:
reduce division "`seq 1 5`"
echo filter:
filter \
"lambda '[ \$1 -gt 5 ]'" \
"`seq 1 10`"
echo map:
map succ "1 2 3 4 5"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment