Re: what did I do wrong here ?
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <[email protected]> |
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