Skip to content

Instantly share code, notes, and snippets.

@jeanjerome
Created May 13, 2023 21:43
Show Gist options
  • Save jeanjerome/a30eb07d4e05e9dc7dc9b5547b705092 to your computer and use it in GitHub Desktop.
Save jeanjerome/a30eb07d4e05e9dc7dc9b5547b705092 to your computer and use it in GitHub Desktop.
Functional Programming in Bash
#!/bin/bash
# Function 1: Convert text to uppercase
to_uppercase() {
echo "$1" | tr '[:lower:]' '[:upper:]'
}
# Function 2: Add a prefix to the text
add_prefix() {
echo "Prefix $1"
}
# Function 3: Display the final text
display_text() {
echo "Final text: $1"
}
# Composition of functions
compose_functions() {
local result="$1"
shift
for func in "$@"; do
result="$($func "$result")"
done
echo "$result"
}
# Using function composition
text="example text"
result=$(compose_functions "$text" to_uppercase add_prefix display_text)
echo "$result"
# Output: Final text: Prefix EXAMPLE TEXT
#!/bin/bash
# Higher-order function to apply a given function to each element of an array
map() {
local func=$1
local array=("${@:2}")
local result=()
for element in "${array[@]}"; do
result+=("$("$func" "$element")")
done
echo "${result[@]}"
}
# Example usage
square() {
local num=$1
echo $((num * num))
}
array=(1 2 3 4 5)
result=($(map square "${array[@]}"))
echo "${result[@]}"
# Output: 1 4 9 16 25
#!/bin/bash
my_function() {
local var="Local"
local -r read_only_var="Read-only"
var="Modified" # Modifying a local variable
read_only_var="Modified" # Attempting to modify an immutable variable
}
my_function
# Output: bash: read_only_var: readonly variable
#!/bin/bash
# Lazy function: Calculates and returns the list of even numbers up to a certain threshold
get_even_numbers_lazy() {
local threshold=$1
local numbers=()
local current=0
while (( current < threshold )); do
numbers+=($current)
current=$((current + 2))
done
echo "${numbers[@]}"
}
# Using the lazy function
numbers=$(get_even_numbers_lazy 10)
echo "Even numbers up to 10: ${numbers[@]}"
# Output: Even numbers up to 10: 0 2 4 6 8
#!/bin/bash
# Pure function to calculate the square of a number
square() {
local num=$1
echo $((num * num))
}
# Example usage
result=$(square 2)
echo "$result"
# Output: 4
#!/bin/bash
# Recursive function to calculate the factorial of a number
factorial() {
local num=$1
if ((num <= 1)); then
echo 1
else
local sub_factorial=$(factorial $((num - 1)))
echo $((num * sub_factorial))
fi
}
# Example usage
echo $(factorial 5)
# Output: 120
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment