maybe monad and friends

maybe - return a tuple of (Nothing) or (Just,value)
maybemap - apply map function when maybe has a value and wrap in another maybe; else when nothing return nothing
maybevalue - return value of maybe; else when nothing return optional default args
This commit is contained in:
tpoindex 2019-09-11 22:47:39 -06:00 committed by Sławomir Śledź
parent 7736a293a0
commit b19ab5180b
2 changed files with 69 additions and 0 deletions

View file

@ -358,3 +358,43 @@ call() {
local args=$@ local args=$@
tup $f $args tup $f $args
} }
maybe() {
if [[ $# -eq 0 ]]; then
local arg
read arg
maybe "$arg"
else
local x="$*"
local value=$(echo $x | strip)
if [[ ${#value} -eq 0 ]]; then
tup Nothing
else
tup Just "$value"
fi
fi
}
maybemap() {
local x
read x
if [[ $(tupl $x) = "Nothing" ]]; then
echo $x
else
local y=$(tupr "$x")
local r=$(echo "$y" | map "$@")
maybe "$r"
fi
}
maybevalue() {
local default="$*"
local x
read x
if [[ $(tupl $x) = "Nothing" ]]; then
echo "$default"
else
echo $(tupr $x)
fi
}

29
test/maybe_test.sh Executable file
View file

@ -0,0 +1,29 @@
#! /bin/bash
testMaybe() {
assertEquals '(Just,1)' "$(maybe 1)"
assertEquals '(Just,1)' "$(echo 1 | maybe)"
assertEquals '(Nothing)' "$(maybe '')"
assertEquals '(Nothing)' "$(maybe ' ')"
assertEquals '(Nothing)' "$(maybe ' ' ' ' ' ')"
assertEquals '(Nothing)' "$(echo | maybe)"
assertEquals '(Just,1 2 3)' "$(maybe 1 2 3)"
assertEquals '(Just,1 2 3)' "$(echo 1 2 3 | maybe)"
}
testMaybemap() {
assertEquals '(Just,3)' "$(echo 1 | maybe | maybemap lambda a . 'echo $(( a + 1 ))' | maybemap lambda a . 'echo $(( a + 1 ))')"
assertEquals '(Nothing)' "$(echo | maybe | maybemap lambda a . 'echo $(( a + 1 ))' | maybemap lambda a . 'echo $(( a + 1 ))')"
assertEquals '(Nothing)' "$(echo 1 | maybe | maybemap lambda a . 'echo $(( a + 1 ))' | maybemap lambda a . 'echo')"
assertEquals '(Nothing)' "$(echo 1 | maybe | maybemap lambda a . 'echo $(( a + 1 ))' | maybemap lambda a . 'echo' | maybemap lambda a . 'echo $(( a + 1 ))')"
}
testMaybevalue() {
assertEquals 3 "$(echo 1 | maybe | maybemap lambda a . 'echo $(( a + 1 ))' | maybemap lambda a . 'echo $(( a + 1 ))' | maybevalue 0)"
assertEquals 0 "$(echo | maybe | maybemap lambda a . 'echo $(( a + 1 ))' | maybemap lambda a . 'echo $(( a + 1 ))' | maybevalue 0)"
assertEquals 'a b c' "$(echo | maybe | maybemap lambda a . 'echo $(( a + 1 ))' | maybemap lambda a . 'echo $(( a + 1 ))' | maybevalue a b c)"
}
. ./shunit2-init.sh