caml-list - the Caml user's mailing list
 help / 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
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 index

Thread overview: 7+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2020-01-07 19:25 rixed [this message]
2020-01-07 20:20 ` Ivan Gotovchits
2020-01-08  6:55   ` rixed
2020-01-08  9:44     ` Jacques Garrigue
2020-01-08 20:32     ` Ivan Gotovchits
2020-01-10  9:50       ` Malcolm Matalka
2020-01-10 19:51         ` Ivan Gotovchits

Reply instructions:

You may reply publically 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

caml-list - the Caml user's mailing list

Archives are clonable: git clone --mirror https://inbox.ocaml.org/caml-list

AGPL code for this site: git clone https://public-inbox.org/ public-inbox