From: Tom <tom.primozic@gmail.com>
To: "Lucas Holland" <hollandlucas@gmail.com>
Cc: caml-list@yquem.inria.fr
Subject: Re: [Caml-list] Simple factorial
Date: Tue, 23 Jan 2007 20:04:00 +0100 [thread overview]
Message-ID: <c1490a380701231104p4eaac657s190fe00c60a1f24e@mail.gmail.com> (raw)
In-Reply-To: <3E3A2218-5AA0-445F-A37D-B12EF4A2F9CB@gmail.com>
[-- Attachment #1: Type: text/plain, Size: 1332 bytes --]
On 23/01/07, Lucas Holland <hollandlucas@gmail.com> wrote:
>
> Hello,
>
> I've just started learning O'Caml. I've written a simple factorial
> function (no checking whether n is 1 etc.):
>
> let rec factorial n =
> n * factorial (n-1);;
>
> When I call this function with let's say 5 as an argument, I get an
> overflow error message.
>
> Any ideas?
>
Well... the problem is, that your function "never ends" - the multiplication
continues into infinity. When you make a call
factorial 5
what actually happens is
5 * factorial (5-1)
5 * factorial 4
5 * 4 * factorial 3
5 * 4 * 3 * factorial 2
5 * 4 * 3 * 2 * factorial 1
5 * 4 * 3 * 2 * 1 * factorial 0
5 * 4 * 3 * 2 * 1 * 0 * factorial (-1)
5 * 4 * 3 * 2 * 1 * 0 * (-1) * factorial (-2)
5 * 4 * 3 * 2 * 1 * 0 * (-1) * (-2) * factorial (-3)
.
.
.
and your function never returns. Checking if n is 1 (or 0) isn't just
neccessary because of the matematical definition of the factorial, but also
because of algorithmic implementation.
The overflow exception you get is generated when a lot of functions are
called (usually this happens in non-tail-recursive list functions with very
big input lists) but don't return, and so they consume all the stack
available.
- Tom
[-- Attachment #2: Type: text/html, Size: 2232 bytes --]
next prev parent reply other threads:[~2007-01-23 20:31 UTC|newest]
Thread overview: 5+ messages / expand[flat|nested] mbox.gz Atom feed top
2007-01-23 18:50 Lucas Holland
2007-01-23 19:04 ` Tom [this message]
2007-01-23 19:10 ` [Caml-list] " robert
2007-01-23 19:11 ` Dário Abdulrehman
2007-01-23 19:50 ` Till Varoquaux
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=c1490a380701231104p4eaac657s190fe00c60a1f24e@mail.gmail.com \
--to=tom.primozic@gmail.com \
--cc=caml-list@yquem.inria.fr \
--cc=hollandlucas@gmail.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox