Caspian Ahlberg
Caspian Ahlberg

Reputation: 976

Declaring an OCaml user-defined type as a function

I am writing a Lisp interpreter in OCaml. This describes my type system:

type atom = Bool of bool
            | Int of int
            | Float of float
            | String of string
            | Symbol of string

type sexpr = Nil
            | Atom of atom
            | Pair of sexpr * sexpr

I want to include functions as first-class values here. For this, I planned a definition that I could add to my atom types, resembling this:

| Function of sexpr -> sexpr

However, since ocamlopt wasn't having a good day, it started complaining:

 make
ocamlopt str.cmxa -o dromedar types.ml lib.ml parser.ml dromedar.ml && ./dromedar
File "types.ml", line 6, characters 23-25:
6 |             | Function of sexpr -> sexpr
                           ^^
Error: Syntax error
make: *** [all] Error 2

When thinking of what would make the most sense, my solution resembles just that (at least to me). Does anyone know how to get this to work?

Upvotes: 0

Views: 103

Answers (1)

Ulugbek Abdullaev
Ulugbek Abdullaev

Reputation: 435

This may be something you're after

type atom = Bool of bool
            | Int of int
            | Float of float
            | String of string
            | Symbol of string
            | Function of (sexpr -> sexpr) (* that's what you want *)


and sexpr = Nil                            (* note that it's "and" not "type")
            | Atom of atom
            | Pair of sexpr * sexpr

and keyword allows mutually recursive definitions for values and types (and modules, but that's experimental at this time, I think).

Upvotes: 1

Related Questions