caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
From: rixed@happyleptic.org
To: caml-list@inria.fr
Subject: [Caml-list] Calling a single function on every member of a GADT?
Date: Tue, 07 Jan 2020 20:24:35 +0100	[thread overview]
Message-ID: <4d2b5367-a869-42bc-9547-b58864c10cf8@www.fastmail.com> (raw)

I'm basically trying to do the equivalent of this simple `fold` function:

---
module Simple =
struct
  type term =
     | Int of int
     | Add
     | App of term * term

  let rec fold i f = function
    | Int _ as t -> f i t
    | Add -> f i Add
    | App (x, y) as t -> f (fold (fold i f x) f y) t
end
---

... but using a GADT:

---
module Gadt =
struct
  type _ term =
     | Int : int -> int term
     | Add : (int -> int -> int) term
     | App : ('b -> 'a) term * 'b term -> 'a term

  let rec fold : type a. 'r -> ('r -> _ term -> 'r) -> 'r = fun i f -> function
    | Int _ as t -> f i t
    | Add -> f i Add
(*
     ^ Error: This pattern matches values of type (int -> int -> int) term
        but a pattern was expected which matches values of type int term
        Type int -> int -> int is not compatible with type int
*)
    | App (x, y) as t -> f (fold (fold i f x) f y) t
end
---

I've tried other variants of the syntax and got many encouragements but no green flag from the type-checker.
Why is the compiler expecting an int term in there? I though the whole point of the `type a. ...` syntax was to allow the matched type to vary from one pattern to the next?
Is there a way to do this?

             reply	other threads:[~2020-01-07 19:25 UTC|newest]

Thread overview: 7+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2020-01-07 19:24 rixed [this message]
2020-01-07 20:21 ` Ivan Gotovchits
2020-01-08  6:54   ` rixed
2020-01-08  9:43     ` Jacques Garrigue
2020-01-08 20:32     ` Ivan Gotovchits
2020-01-10  9:49       ` Malcolm Matalka
2020-01-10 19:52         ` Ivan Gotovchits

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=4d2b5367-a869-42bc-9547-b58864c10cf8@www.fastmail.com \
    --to=rixed@happyleptic.org \
    --cc=caml-list@inria.fr \
    /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).