Skip to content

Instantly share code, notes, and snippets.

@gilgamesh2k
Created August 9, 2013 02:57
Show Gist options
  • Save gilgamesh2k/6190841 to your computer and use it in GitHub Desktop.
Save gilgamesh2k/6190841 to your computer and use it in GitHub Desktop.
Functional bash, just a little :-) add to .bashrc: source fun.sh
#!/bin/bash
print() {
while read x; do
echo $x
done
}
list() {
for elem; do
echo "$elem"
done
}
unlist() {
foldl λ a b → 'echo "$a $b"'
}
map() {
while read x; do
echo $x | $@
done
}
foldl() {
f="$@"
read acc;
while read elem; do
acc="$(echo -e "$acc\n$elem" | $f)"
done
echo "$acc"
}
scanl() {
f="$@"
read acc
while read elem; do
acc="$(echo -e "$acc\n$elem" | $f)"
echo "$acc"
done
}
function lambda () {
lam() {
for last; do
shift
if [[ $last = "." || $last = ":" || $last = "->" || $last = "→" ]]; then
echo "$@"
return
else
echo "read $last;"
fi
done
}
y="stdin"
for i in "$@"; do
if [[ $i = "." || $i = ":" || $i = "->" || $i = "→" ]]; then
y="args"
fi
done
if [[ "$y" = "stdin" ]]; then
read fun
eval $(lam "$@ → $fun")
else
eval $(lam "$@")
fi
}
### Let's define some "functional" functions :) ###
function λ() { lambda "$@"; }
sum() {
foldl λ a b → 'echo $(($a + $b))'
}
product() {
foldl λ a b → 'echo $(expr $a \* $b)'
}
factorial() {
seq 1 $1 | product
}
special-lambda() {
echo λ
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment