What is equivalent to directive like ghci in OCaml?

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

For example, if I want to know the type \ fgh -> g (hf) , I can use the directive in the ghci interpreter as follows:

 Prelude> :t \ fgh -> g (hf) \ fgh -> g (hf) :: t2 -> (t1 -> t) -> (t2 -> t1) -> t 

Is there an equivalent of this for OCaml?

+6
source share
2 answers

You can find utop suitable for this. This is an extended version of the standard OCaml toplevel, but with:

  • more reasonable defaults for interactive use (with shortcuts enabled)
  • automatic evaluation of some top-level mods, such as Lwt or Async I / O (therefore, input to int Deferred.t or int Lwt.t will return int at the top level)
  • interactive history and completion of the module, as well as everything that the editor likes.

There are two ways to find the type of something. For the value, simply enter the expression at the top level:

 $ 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 that can print this for you.

 $ 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 latter shows that the reference type ref is just syntactic sugar for a field with one contents field changed).

Another common trick to quickly reset a module definition is its alias for the 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 quickly install utop through opam install utop . We recommend this in Real World OCaml as the preferred interactive editor for beginners rather than vanilla OCaml toplevel.

+13
source

Just enter the function in the OCaml interpreter, and its type will be automatically displayed

 # fun fgh -> g (hf);; - : 'a -> ('b -> 'c) -> ('a -> 'b) -> 'c = <fun> 
+5
source

Source: https://habr.com/ru/post/955896/


All Articles