[英]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 . 在ghci中,您可以使用type指令找出任何表达式的类型 。
For example, if I want to find out the type of \\ fgh -> g (hf)
, I can use the directive in the ghci interpreter like this: 例如,如果我想找出
\\ fgh -> g (hf)
,我可以在ghci解释器中使用这样的指令:
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? OCaml是否有相同的功能?
You may find the utop toplevel useful for this. 您可能会发现utop toplevel对此有用。 It's an enhanced version of the standard OCaml toplevel, but with:
它是标准OCaml顶级的增强版本,但具有:
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(1.7+)也有一个
#typeof
指令,可以为你打印出来。
$ 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). (最后一个显示
ref
引用类型只是具有单个可变contents
字段的字段的语法糖)。
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
. 您可以通过
opam install utop
快速opam install utop
。 We recommend this in Real World OCaml as the preferred interactive editor for newcomers, instead of the vanilla OCaml toplevel. 我们建议在Real World OCaml中将其作为新手的首选交互式编辑器,而不是vanilla OCaml toplevel。
Just type the function into the OCaml interpreter, and its type is automatically displayed 只需在OCaml解释器中键入该函数,就会自动显示其类型
# fun f g h -> g (h f);;
- : 'a -> ('b -> 'c) -> ('a -> 'b) -> 'c = <fun>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.