Add MVP for functional programming

This commit is contained in:
Denis Isidoro 2019-09-25 13:09:47 -03:00 committed by Denis Isidoro
parent e523febf0c
commit 093bac0e9f
3 changed files with 60 additions and 0 deletions

32
src/func.sh Normal file
View file

@ -0,0 +1,32 @@
#!/usr/bin/env bash
func::list() {
for x in "$@"; do
echo "$x"
done
}
func::map() {
local -r fn="$1"
shift
for x in $(cat); do
"$fn" "$x"
done
}
func::reduce() {
local -r fn="$1"
local state="$2"
local -r coll="$(cat)"
local -r x="$(echo "$coll" | head -n1)"
if [ -z "$x" ]; then
echo "$state"
else
local -r new_state="$("$fn" "$state" "$x")"
local -r new_coll="$(echo "$coll" | tail -n +2)"
echo "$new_coll" | func::reduce "$fn" "$new_state"
fi
}

View file

@ -7,6 +7,7 @@ fi
source "${SCRIPT_DIR}/src/arg.sh"
source "${SCRIPT_DIR}/src/cheat.sh"
source "${SCRIPT_DIR}/src/dict.sh"
source "${SCRIPT_DIR}/src/func.sh"
source "${SCRIPT_DIR}/src/health.sh"
source "${SCRIPT_DIR}/src/misc.sh"
source "${SCRIPT_DIR}/src/opts.sh"

27
test/func_test.sh Normal file
View file

@ -0,0 +1,27 @@
#!/usr/bin/env bash
inc() {
local -r x="$1"
echo $((x+1))
}
sum() {
local -r x="$1"
local -r y="$2"
echo $((x*y))
}
func_map() {
func::list 1 2 3 \
| func::map inc \
| test::equals "$(func::list 2 3 4)"
}
func_reduce() {
func::list 1 2 3 \
| func::reduce sum 10 \
| test::equals 60
}
test::run "map works" func_map
test::run "reduce works" func_reduce