Skip to content

Instantly share code, notes, and snippets.

@zonuexe
Created January 19, 2012 05:05
Show Gist options
  • Save zonuexe/1638092 to your computer and use it in GitHub Desktop.
Save zonuexe/1638092 to your computer and use it in GitHub Desktop.
シェルスクリプトで再帰
#!/usr/bin/env bash
function vecho () {
if [ $VERBOSE ]
then echo $@ >&2
fi
}
function _fst () {
vecho _fst: 1=$1 >&2
declare -r n=$(echo $1 | cut -d' ' -f1)
vecho _fst: n=$n >&2
echo $n
}
function _snd () {
vecho _snd: 1=$1 >&2
declare -r n=$(echo $1 | cut -d' ' -f2-)
vecho _snd: n=$n >&2
declare -r q=$(echo "$n" | grep ' ')
vecho _snd: q=$q >&2
if [ "$q" ]
then echo $n
else echo ''
fi
}
function _sum () {
declare -r xs="$1"
vecho _sum: xs=$xs >&2
case $xs in
'' )
echo 0 ;;
* )
declare -r y=$(_fst "$xs")
declare -r ys=$(_snd "$xs")
vecho _sum: y=$y >&2
vecho _sum: ys=$y >&2
echo $(( $y + $(_sum "$ys") )) ;;
esac
}
export VERBOSE=""
#export VERBOSE="1"
declare -r last=$1
declare -r seq=$(seq 1 1 $last)
_sum "$seq"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment