Jason Yeo
Jason Yeo

Reputation: 3702

What's the equivalent of ghci's type directive in OCaml?

In ghci, you can find out the type of any expression using the type directive.

For example, if I want to find out the type of \ f g h -> g (h f), I can use the directive in the ghci interpreter like this:

Prelude> :t \ f g h -> g (h f)
\ f g h -> g (h f) :: t2 -> (t1 -> t) -> (t2 -> t1) -> t

Is there an equivalent of this for OCaml?

Upvotes: 7

Views: 808

Answers (2)

Anil Madhavapeddy
Anil Madhavapeddy

Reputation: 223

You may find the utop toplevel useful for this. It's an enhanced version of the standard OCaml toplevel, but with:

  • more sensible defaults for interactive use (short-paths enabled)
  • automatic evaluation of some top-level monads, such as Lwt or Async I/O (so typing in a int Deferred.t or int Lwt.t will return the int at the toplevel)
  • interactive history and module completion and all that editor goodness.

There are two ways to find the type of something. For a value, just enter the expression into the toplevel:

$ utop
# let x = 1 ;;
val x : int = 1
# x ;;
- : int = 1

This works for values, but not for type definitions. utop (1.7+) also has a #typeof directive which can print this out for you, though.

$ utop
# #typeof Unix.sockaddr
type Unix.sockaddr = ADDR_UNIX of string | ADDR_INET of Unix.inet_addr * int
# #typeof ref
type 'a Pervasives.ref = { mutable contents : 'a; }

(the last one shows you that the ref reference type is just syntactic sugar for a field with a single mutable contents field).

Another common trick to quickly dump a module definition is to alias it to a new module.

$ utop
# module L = List ;;
module L : sig
  val hd : 'a list -> 'a
  val tl : 'a list -> 'a list
  val nth : 'a list -> int -> 'a
  <etc>

You can install utop quickly via opam install utop. We recommend this in Real World OCaml as the preferred interactive editor for newcomers, instead of the vanilla OCaml toplevel.

Upvotes: 14

Chris Taylor
Chris Taylor

Reputation: 47392

Just type the function into the OCaml interpreter, and its type is automatically displayed

# fun f g h -> g (h f);;
- : 'a -> ('b -> 'c) -> ('a -> 'b) -> 'c = <fun>

Upvotes: 5

Related Questions