o'caml recursion not working right
Author |
Message |
richcash
|
Posted: Mon Apr 09, 2007 2:45 am Post subject: o'caml recursion not working right |
|
|
I just started O'Caml tonight, so I apologize if it's a bit of an obvious question.
code: | # let rec factorial a =
if a == 1 then a else a * factorial (a-1);;
val factorial : int -> int = <fun>
# factorial 4;;
- : int = 24
# factorial 13;;
- : int = -215430144 |
I'm not sure why my function there is returning a negative value. I know that once the result becomes too big, the function will result 0, but I can't see why it would ever return a negative value like that.
I also tried it for another recursive function and the same thing happened once I got high enough.
code: | # let rec f x power =
if power == 1 then x else x * f x (power-1);;
val f : int -> int -> int = <fun>
# f 4 3;;
- : int = 64
# f 4 15;;
- : int = -1073741824 |
Could someone just tell me if I'm doing something wrong here.
Thanks in advance.  |
|
|
|
|
 |
Sponsor Sponsor

|
|
 |
wtd
|
Posted: Mon Apr 09, 2007 3:01 am Post subject: RE:o\'caml recursion not working right |
|
|
O'Caml's integer datatype has some interesting issues with overflow.
You'll want to use some form of bignum module. |
|
|
|
|
 |
richcash
|
Posted: Mon Apr 09, 2007 3:10 am Post subject: Re: o'caml recursion not working right |
|
|
Oh, well that's weird. An error would be better than resulting an incorrect value I think. Too bad it's not more like Ruby (automatically converts back and forth! )
Thanks for clearing that up! |
|
|
|
|
 |
haskell
|
Posted: Mon Apr 09, 2007 11:20 am Post subject: RE:o\'caml recursion not working right |
|
|
When a program does EXACTLY what its told, debugging and such is quite easy, as you showed and wtd demonstrated. So adding such features would make OCaml less practical in a professional environment, making it unattractive and strictly academic, which it isn't and shouldn't be.
These sorts of things are features, not errors. They are a God-send for programmers and keep us warm inside. |
|
|
|
|
 |
wtd
|
Posted: Mon Apr 09, 2007 11:34 am Post subject: Re: o'caml recursion not working right |
|
|
or... O'Caml and Ruby are just different sorts of languages, each of which has advantages and disadvantages.
 |
|
|
|
|
 |
|
|