3

我已经搜索了一段时间,但找不到解决方案。这可能是一个我无法弄清楚的简单语法问题。

我有一个类型:

# type ('a, 'b) mytype = 'a * 'b;;

我想创建一个类型的变量string string sum

# let (x:string string mytype) = ("v", "m");;
Error: The type constructor mytype expects 2 argument(s),
   but is here applied to 1 argument(s)

我尝试了不同的方式在类型参数周围加上括号,我得到了几乎相同的错误。

但是,它适用于单个参数类型,所以我想有一些我不知道的语法。

# type 'a mytype2 = string * 'a;;
# let (x:string mytype2) = ("hola", "hello");;
val x : string mytype2 = ("hola", "hello")

有人可以告诉我如何使用两个参数来做到这一点吗?

4

2 回答 2

3

你应该写

let (x: (string, string) mytype) = ("v", "m");;

那就是mytype参数是一对。您甚至可以删除不需要的括号:

let x: (string, string) mytype = "v", "m";;
于 2014-02-13T09:38:24.097 回答
1

值得注意的是,您的类型mytype只是一对的同义词,因为它没有任何构造函数。所以你可以说let x = ("v", "m")

$ ocaml
        OCaml version 4.01.0

# type ('a, 'b) mytype = 'a * 'b;;
type ('a, 'b) mytype = 'a * 'b
# let x = ("v", "m");;
val x : string * string = ("v", "m")
# (x : (string, string) mytype);;
- : (string, string) mytype = ("v", "m")

关键是这两种类型string * string(string, string) mytype是同一类型。

于 2014-02-13T15:42:54.497 回答