使用只有一个元组值的变体类型构造函数 [英] Using a variant type constructor with just one tuple value
问题描述
# type foo = Foo of int * int
# let t = (1, 2)
# Foo t
Error: The constructor Foo expects 2 argument(s),
but is applied here to 1 argument(s)
我必须做 Foo(1,2)
才能避免这个错误,即使 t 有合适的类型吗?
How is it that I must do Foo (1, 2)
to avoid that error even t has the appropriate type?
推荐答案
在我看来,这是OCaml语法的一个麻烦的部分。尽管它的外观,构造函数Foo不需要2元组作为其参数。它在语法上需要括号中的两个值 - 但它们不是元组。因此, t
的类型错误。这个工作的方式是:
This is one of the troubling parts of OCaml syntax, in my opinion. Despite the way it looks, the constructor Foo doesn't require a 2-tuple as its argument. It requires, syntactically, two values in parentheses--but they aren't a tuple. So it's simply the case that t
has the wrong type. The way to make this work is to say:
let (a, b) = t in Foo (a, b)
问题真的是括号用于两个不同的东西一旦你习惯了这一点,它并不难处理。
The problem really is that parentheses are being used for two different things (or so I claim). Once you get used to this it's not so difficult to deal with.
编辑:如果你 Foo取单个元组,而不是两个单独的值,你可以这样定义:
Edit: if you want the constructor Foo to take a single tuple, rather than two separate values, you can define it like this:
type foo = Foo of (int * int)
然后,其余的原始代码将工作。
Then the rest of your original code will work.
这篇关于使用只有一个元组值的变体类型构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!