Re: what did I do wrong here ?
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <[email protected]> |
Thanks everybody, I see now what I have done wrong. Next problem making this work with a power function. Roelof Matthieu Dubuget [email protected] [ocaml_beginners] schreef op 14-10-2014 21:18: let me try to explain the function another way. It does not work as you explained, but the other way (from n to 0). ```ocaml let rec sum = function | 0 -> 0 | n -> n + sum(n - 1) ``` sum 3 is replaced by 3 + sum 2 which is replaced by 3 + 2 + sum 1 which is replaced by 3 + 2 + 1 + sum 0 whis is replaced by 3 + 2 + 1 + 0 The factorial function you showed is also working this way. We can try to go the other way… ```ocaml let sum n = (* we hide a func inside *) let rec embeded_sum step result = if step = n (* when n is reached *) then result + n (* finish with the final result by summing the previous one with n *) else sum (step + 1) (step + result) in (* else, increment the result with step, and go to the next one *) embeded_sum 0 0 (* start from 0, with the result 0 *) ```` Here are the values of step and result. step result 0 0 1 0 2 1 3 3 4 6 5 10 ... -- Matthieu Dubuget Guide d’autodéfense numérique : http://guide.boum.org __._,_.___ ---------- Posted by: Roelof Wobben <[email protected]> ---------- Reply via web post • Reply to sender • Reply to group • Start a New Topic • Messages in this topic (7) Archives up to December 31, 2011 are also downloadable at http://www.connettivo.net/cntprojects/ocaml_beginners The archives of the very official ocaml list (the seniors' one) can be found at http://caml.inria.fr Attachments are banned and you're asked to be polite, avoid flames etc. Visit Your Group https://groups.yahoo.com/neo;_ylc=X3oDMTJkcm91N2YzBF9TAzk3NDc2NTkwBGdycElkAzQ5OTkxOTQEZ3Jwc3BJZAMxNzA1MDA2NzY0BHNlYwNmdHIEc2xrA2dmcARzdGltZQMxNDEzMzE3MDk3 • Privacy • Unsubscribe • Terms of Use . __,_._,___