Bash functional: Difference between revisions
From wikinotes
(→Map) |
(→Reduce) |
||
Line 50: | Line 50: | ||
= Reduce = | = Reduce = | ||
<blockquote> | <blockquote> | ||
{{ TODO | | |||
wip, but this is general idea | |||
}} | |||
<syntaxhighlight lang="bash"> | |||
reduce() { | |||
# callable/params must accept aggregate as 2nd-last param, and input as last param. | |||
# | |||
# EXAMPLE: | |||
# sum() { echo $(($1 + $2)) } | |||
# echo {1..10} | tr ' ' '\n' | reduce sum 0 | |||
local callable="${@:1:$#-1}" | |||
local aggregate="${@[$#-1]}" | |||
local input | |||
while read -r input; do | |||
aggregate="$("${callable[@]}" "${aggregate}" "${input}")" | |||
done | |||
echo "${aggregate}" | |||
} | |||
</syntaxhighlight> | |||
</blockquote><!-- Reduce --> | </blockquote><!-- Reduce --> |
Revision as of 19:19, 11 December 2022
Filter
# filters out results not matching 'grep foo' find . \ | while read line; do \ echo $line | grep foo && echo "$line"; \ done
Map
NOTE:
If your callable accepts parameter as stdin, you don't need map (ex. grep/sed work just fine from stdin).
map() { # Call callable/params($*), passing each each STDIN line as the last parameter local input while read -r input; do "$@" "${input}" done }Example
print_if_divisible_by_2() { if [ $(($1 % 2)) -eq 0 ] ; then echo "$1:yes" else echo "$1:no" fi } echo {1..4} | tr ' ' '\n' | map print_if_divisible_by_2 #> 1:no #> 2:yes #> 3:no #> 4:yes
Reduce
TODO:
wip, but this is general idea
reduce() { # callable/params must accept aggregate as 2nd-last param, and input as last param. # # EXAMPLE: # sum() { echo $(($1 + $2)) } # echo {1..10} | tr ' ' '\n' | reduce sum 0 local callable="${@:1:$#-1}" local aggregate="${@[$#-1]}" local input while read -r input; do aggregate="$("${callable[@]}" "${aggregate}" "${input}")" done echo "${aggregate}" }