Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get type information in interactive Ocaml?

Tags:

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?

like image 396
Alexey Alexandrov Avatar asked Jan 12 '13 07:01

Alexey Alexandrov


People also ask

What is type A in OCaml?

The type 'a is a type variable, and stands for any given type. The reason why sort can apply to lists of any type is that the comparisons (=, <=, etc.) are polymorphic in OCaml: they operate between any two values of the same type. This makes sort itself polymorphic over all list types.

How to return a function in OCaml?

OCaml doesn't have a return keyword — the last expression in a function becomes the result of the function automatically.

What is :: In OCaml?

Note that :: is technically a type constructor which is why you can use it in both patterns and expressions.

How to exit toplevel OCaml?

In a terminal window, type utop to start the interactive OCaml session, commonly called the toplevel. Press Control-D to exit the toplevel. You can also enter #quit;; and press return. Note that you must type the # there: it is in addition to the # prompt you already see.


2 Answers

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.

like image 157
ivg Avatar answered Sep 17 '22 15:09

ivg


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);;
like image 42
codablank1 Avatar answered Sep 19 '22 15:09

codablank1