caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
From: "Andreas Rossberg" <AndreasRossberg@web.de>
To: <caml-list@inria.fr>, "Mike Hamburg" <hamburg@fas.harvard.edu>
Subject: Re: [Caml-list] type-checking difficulties in recursive functions
Date: Wed, 27 Apr 2005 22:13:44 +0200	[thread overview]
Message-ID: <001b01c54b65$b28bbe90$14b2a8c0@wiko> (raw)
In-Reply-To: <fe301a3cb44607962b354db7d852e4c7@fas.harvard.edu>

Mike Hamburg <hamburg@fas.harvard.edu> wrote:
>
> let rec foo p x =
> if p then x
> else
> let something = foo false "Hello"
> in x;;
> val foo : bool -> string -> string = <fun>
>
> Now, foo is actually safe as a function from bool -> 'a -> 'a, but the
> recursive declaration doesn't generalize and so the checker doesn't
> realize this.  With magic, I can get the right type relatively safely

What you want is "polymorphic recursion". Unfortunately, type inference for
polymorphic recursion is undecidable in general. Haskell allows polymorphic
recursion if you annotate the type, so that it doesn't have to be inferred.
In OCaml, this is not possible directly, but you can achieve the same effect
by going through a record and using the more recent feature of polymorphic
record fields, plus OCaml's let rec "language extension":

  type foo_rec = {foo : 'a.bool->'a->'a}
  let rec foo_rec = {foo = fun p x -> if p then x else let _ = foo_rec.foo
false "" in x}
  let foo = foo_rec.foo

Not particularly nice, but does what you want.

Hope this helps,

  - Andreas


  reply	other threads:[~2005-04-27 20:13 UTC|newest]

Thread overview: 3+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2005-04-27 19:14 Mike Hamburg
2005-04-27 20:13 ` Andreas Rossberg [this message]
2005-04-27 20:55   ` [Caml-list] " brogoff

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='001b01c54b65$b28bbe90$14b2a8c0@wiko' \
    --to=andreasrossberg@web.de \
    --cc=caml-list@inria.fr \
    --cc=hamburg@fas.harvard.edu \
    /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;
as well as URLs for NNTP newsgroup(s).