Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Last active July 23, 2019 15:17
Show Gist options
  • Save coderofsalvation/831c5398e135c4373788 to your computer and use it in GitHub Desktop.
Save coderofsalvation/831c5398e135c4373788 to your computer and use it in GitHub Desktop.
minimal functional programming in bash with associative array, prevent pyramid of doom
#!/bin/bash
# higher order functions for bash
array(){
declare -A "$@"
}
# foreach
# example:
# array foo
# foo[0]="one" foo[1]="two" foo["bar"]="BAR"
# bar(){ echo "$1 -> $2"; }
# foreach foo bar
# foreach foo keys | grep [0-1] | map pick foo
foreach(){
eval "for i in \"\${!$1[@]}\"; do $2 \"\$i\" \"\$( echo \"\${$1[\$i]}\" )\"; done"
}
keys(){
echo "$1"
}
values(){
echo "$2"
}
pick(){
[[ ! -n $2 ]] && return 1 || eval "echo \${$1[$2]}"
}
# maps a pipe stream to individual calls
# example:
# foreach foo values | map echo
map(){
set +m ; shopt -s lastpipe
cat - | while read line; do "$@" "$line"; done
}
# compose function out of 2 functions
# example:
# compose functionname func2 func1
# functionname "this is input"
compose() {
result_fun=$1; shift ; f1=$1; shift ; f2=$1; shift
eval "$result_fun() { $f1 \"\$($f2 \"\$*\")\"; }"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment