Created
October 31, 2021 21:10
-
-
Save Xophmeister/ad8e7b849aff60f3abb92858bc599928 to your computer and use it in GitHub Desktop.
Functional programming...in Bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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