23

I am using Ocaml of version 4. When I define interactively some type, the interpreter prints out string representation of the type immediately after that:

# type foo = Yes | No;;         <-- This is what I entered
type foo = Yes | No             <-- This is what interpreter bounced

But after I type more definitions, sometimes I want to see the text representation of the type again.

In Haskell, I could type ":t foo".

How can I do this in Ocaml?

Alexey Alexandrov
  • 2,951
  • 1
  • 24
  • 24
  • 1
    From a more general point of view, you might want to try more advanced tools than just the toplevel. There are the Tuareg mode in emacs, Typerex, OcalIDE and many more. Some of them provide a functionality to jump to the place where the type foo is defined, which might be a way to answer your question. – jrouquie Jan 12 '13 at 13:56
  • 2
    if you've not already using it, I can highly recommend that you use utop as your top-level instead of standard one that comes with OCaml, – Heidi Feb 07 '13 at 16:48

3 Answers3

17

In utop you can use the #typeof directive:

#typeof "list";;
type 'a list = [] | :: of 'a * 'a list 

You can put values and types inside double quotes:

let t = [`Hello, `World];;
#typeof "t";;
val t : ([> `Hello ] * [> `World ]) list   

P.S. And even better solution would be to use merlin.

cic
  • 7,310
  • 3
  • 23
  • 35
ivg
  • 34,431
  • 2
  • 35
  • 63
  • hey, thanks this was helpful. I've installed Merlin into Vim as per the instructions on the GitHub, but what do you have to do _within_ Vim to get the type of an expression? – ofey73 Apr 10 '19 at 00:53
2

As far as I know, there is actually no way in Ocaml to retrieve type information under a string form

You'll have to build a pattern matching for each of your type

type foo = Yes | No;;

let getType = function
  |Yes -> "Yes"
  |No -> "No"    
  ;;

let a = Yes;;
print_string (getType a);;
codablank1
  • 6,055
  • 5
  • 19
  • 29
1

If you're using a recent version of ocaml (e.g. 4.14) or utop you can use their #show directive:

utop> let x = 5;;
val x : int = 5
utop> #show x;;
val x : int
utop> #show (+);;
external ( + ) : int -> int -> int = "%addint"
Bozhidar Batsov
  • 55,802
  • 13
  • 100
  • 117