Skip to content

Instantly share code, notes, and snippets.

@Xophmeister
Created October 31, 2021 21:10
Show Gist options
  • Save Xophmeister/ad8e7b849aff60f3abb92858bc599928 to your computer and use it in GitHub Desktop.
Save Xophmeister/ad8e7b849aff60f3abb92858bc599928 to your computer and use it in GitHub Desktop.
Functional programming...in Bash
#!/usr/bin/env bash
map() {
local fn="$1"
local input
while read -r input; do
"${fn}" "${input}"
done
}
reduce() {
local fn="$1"
local init="$2"
local input
local output="${init}"
while read -r input; do
output="$("${fn}" "${output}" "${input}")"
done
echo "${output}"
}
filter() {
local fn="$1"
local input
while read -r input; do
"${fn}" "${input}" && echo "${input}"
done
}
add() {
echo $(( $1 + $2 ))
}
multiply() {
echo $(( $1 * $2 ))
}
concat() {
echo "${1}${2}"
}
increment() {
echo $(( $1 + 1 ))
}
square() {
echo $(( $1 * $1 ))
}
even() {
return $(( $1 % 2 ))
}
sum() {
reduce add 0
}
map increment | map square | filter even | sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment