OCaml - 什么数据类型是有的和没有的? [英] OCaml - What data type is some and none?

查看:70
本文介绍了OCaml - 什么数据类型是有的和没有的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在列表中使用 SomeNone 组合,列表的数据类型是什么?它总是 'a 吗?或者 Some/None 是否有某种类型?

If I am using Some and None combo in a list what would be the data type of the list? Is it always 'a? Or is there some sort of a type for Some/None?

let listVar : (* type here *) list = [Some 4; Some 3; None; Some 2];;

如果我输入 int 它会给我错误:

If I put int it gives me error:

该表达式的类型为 int option * int option * 'a option * int选项,但此处与 int 类型一起使用

This expression has type int option * int option * 'a option * int option but is here used with type int

当我输入 'a 时,它编译得很好,但是 basicOCaml 教程 说(我参考了其他语言来更好地解释我的问题):

When I put 'a it compiles fine but the basic OCaml tutorial says (I made references to other languages to explain my question better):

目前还不清楚为什么多态函数有用,但它们非常有用也很常见,所以我们稍后会讨论它们.(提示:多态有点像 C++ 中的模板或泛型Java 1.5).

It won't be clear yet why polymorphic functions are useful, but they are very useful and very common, and so we'll discuss them later on. (Hint: polymorphism is kind of like templates in C++ or generics in Java 1.5).

我认为这就像其他语言中的引用/指针,这实际上是有道理的.但是现在,我真的不明白None 是什么类型.Some 也一样.

I thought this was like reference/pointer in other languages, which actually made sense. But now, I really don't understand what type is None. Same goes with Some.

另外,我知道我应该在一个问题中问两个问题,但是这个问题与上一个问题有很强的联系.Some的意义是什么?我通常看到它在使用 None 时使用.如果我在没有 Some 的情况下实现上面的列表,它仍然可以编译,但列表结构没有选项"标志,我猜这意味着可选(我似乎无法在互联网上找到任何关于此的内容).有人能给我提供一个有用的案例吗?

Also, I know I should ask two questions in one question, but this one has a strong relation to the previous question. What is the point of Some? I usually see it used when None is used. If I implement the above list without Some, it still compiles but the list structure doesn't have the "option" flag, which I am guessing means optional (I cant seem to find anything on the internet regarding this). Can someone provide me with one case this is useful?

推荐答案

你这里写的是一个 (int option * int option * 'a option * int option) list 类型的值,即四元组列表,其中前两个组件是可选整数,下一个是多态的(Some case 尚未定义),最后一个是可选整数.这是因为 , 是元组分隔符.列表分隔符是 ; 所以我猜你想写

What you have written here is a value of type (int option * int option * 'a option * int option) list, i.e. a list of quadruplets in which the first two component are optional integer, the next one is polymorphic so far (the Some case is undefined yet) and the last one is an optional integer. This is because , is the tuple separator. The list separator is ; so I guess you wanted to write

let listVar = [Some 4; Some 3; None; Some 2];;

类型为(int option) list.每当您将 SomeNone'a 类型的任意值一起使用时,您将获得 'a 选项 类型的值>.

Which has type (int option) list. Whenever you use Some or None with an arbitrary value of type 'a you get a value of type 'a option.

这篇关于OCaml - 什么数据类型是有的和没有的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆