Ocaml 中带有参数的类型数组
我在 Ocaml 中有一个作业要做...
我的老师说我们必须使用这两种类型:
type 'a zapis = Prazen | Zapis of string * 'a;;
type 'a asocpolje = 'a zapis array;;
我的问题是当我创建一个数组时:
# let a = Array.make 5 Prazen;;
val a : '_a zapis array = [|Prazen; Prazen; Prazen; Prazen; Prazen|]
我不知道可以在这个数组中插入什么值...
a.(0)<-???
可以有人告诉我哪个值可以插入到这个数组中?
I have a homework exercise to do in Ocaml...
My teacher said that we must use these 2 types:
type 'a zapis = Prazen | Zapis of string * 'a;;
type 'a asocpolje = 'a zapis array;;
My problem is that when I create an array:
# let a = Array.make 5 Prazen;;
val a : '_a zapis array = [|Prazen; Prazen; Prazen; Prazen; Prazen|]
I don't know what values can be inserted in this array...
a.(0)<-???
Can someone tell me which value can be inserted in this array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在向数组添加任何内容之前,类型尚未完全定义。这反映在数组指示的类型中:
val a : '_a zapis array = [|Prazen;普拉赞;普拉赞;普拉赞; Prazen|]
如果你仔细观察,你会发现你作为类型参数给出的
'a
已经变成了'_a
(注意_< /代码>)。这种类型的意思是“某种类型,但我还不知道是哪一种”。与
'a
相反,'a
表示任何类型。这意味着此时您可以插入任何类型的 Zapi。执行此操作后,您只能插入该特殊类型的 Zapi(在其他类型中,
'_a
会消失并替换为正确的类型)。因此,如果您这样做,
a
将成为int zapis 数组
,并且从那时起只接受整数。如果你这样做,
它将成为一个
字符串 zapis 数组
,之后只接受字符串。Until you add anything to the array the type is not fully defined. This is reflected in the type indicated for the array:
val a : '_a zapis array = [|Prazen; Prazen; Prazen; Prazen; Prazen|]
If you look closely you will see that the
'a
you gave as type parameter has become a'_a
(note the_
). This type means "some type, but I do not know which one yet". As opposed to'a
which means any type.This means at this point you can insert any kind of Zapis. Once you do that, you can only insert Zapis of that special type (in further types the
'_a
goes away and is replaced with the correct type).So if you do
a
will become aint zapis array
and only accept ints from that moment on.if you do instead
it will become a
string zapis array
only accept strings afterwards.'a asocpolje
和'a zapis array
是相同类型。根据打字机推断定义的准确程度,您将得到其中之一,但它们是完全相同的。'a asocpolje
只是'a zapis array
的别名,而不是新类型。您可以通过使用显式类型注释来帮助 OCaml 打印正确的类型信息:
但是我不鼓励这种做法。它以不明显的方式表现(例如,这里
'a
的含义可能令人惊讶,它不强制执行多态性),并且您确实试图在没有的地方做出改变(类型相同)。如果您确实想要区分这两种类型,则应该将'a asocpolje
定义为新的代数类型(只有一种情况):'a asocpolje
and'a zapis array
are the same type. Depending on how exactly the typer infer your definitions, you will get one or the other, but they're exactly equivalent.'a asocpolje
is just an alias for'a zapis array
, not a new type.You can help OCaml print the right type information by using an explicit type annotation :
I would however discourage this practice. It behaves in non-obvious ways (eg. the meaning of
'a
here may be surprising, it does not enforce polymorphism) and you're really trying to make a difference where there isn't (the types are the same). If you really want a distinction between both types, you should define'a asocpolje
as a new algebraic type (with only one case):