scheme - Simple Recursion? -
i'm new programming , have had hard time understanding recursion. there's problem i've been working on can't figure out. don't understand how solvable.
"define procedure plus takes 2 non-negative integers , returns sum. procedures (other recursive calls plus) may use are: zero?, sub1, , add1.
i know built in functions in scheme, know they're possible solve, don't understand how. recursion tricky!
any appreciated! =] thanks
i'm working in petite chez scheme (with swl editor)
recursion important concept in software development. don't know (petit chez) scheme approach general angle.
the concept of recursive function repeat same task on , on again until reach limiting boundary. taking first question, have 2 numbers , need add them together. however, have ability add 1 number or subtract 1 number. have literal value zero.
so. consider numbers 2 buckets. each have 10 stones in them. want "add" 2 buckets together. permitted move 1 stone @ time (i.e. can't grab handful or tip 1 bucket other).
lets want move left bucket right bucket, 1 stone @ time. going have do?
first, have take 1 stone left bucket, i.e. using sub1
remove 1 stone bucket. add same stone right bucket, i.e. add1
right bucket.
now in loop, don't know how many stones there in given solution. want "take 1 stone left bucket, put in right bucket , repeat until there no stones in left bucket.' case of there being no stones in left bucket called "base case". it's point @ ok, i'm done now.
a pseudocode example of situation (using plus, add1, sub1 , zero):
plus(leftbucket, rightbucket) { if(leftbucket == zero) // check if left bucket empty yet { // left bucket empty, we've moved stones return rightbucket; // right bucket must full } else { // still have stones in left bucket, remove 1, // put in right bucket, repeat. return plus(sub1(leftbucket), add1(rightbucket)); } }
if still need more help, let me know, can run through other examples looks it's homework problem , recursion incredibly important understand don't want give answers.
Comments
Post a Comment