How to get type information in interactive Ocaml?
Asked Answered
T

3

24

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?

Trainee answered 12/1, 2013 at 7:33 Comment(2)
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.Govan
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,Salcido
S
18

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.

Styles answered 5/5, 2014 at 13:24 Comment(1)
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?Greensand
N
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);;
Niphablepsia answered 15/1, 2013 at 13:7 Comment(0)
T
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"
Torchier answered 3/4, 2023 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.