mirror of
https://github.com/denisidoro/navi
synced 2025-02-16 12:38:28 +00:00
Add MVP for functional programming
This commit is contained in:
parent
e523febf0c
commit
093bac0e9f
3 changed files with 60 additions and 0 deletions
32
src/func.sh
Normal file
32
src/func.sh
Normal 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
|
||||
}
|
|
@ -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
27
test/func_test.sh
Normal 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
|
Loading…
Add table
Reference in a new issue