OCaml List 数据类型
OCaml 的 List 数据类型,相当于Java 的List。我们看下实例
utop # let netrcItemList: netrcItem list = [];;
val netrcItemList : netrcItem list = []
utop # netrcItemList @ c
;;
Error: This expression has type netrcItem
but an expression was expected of type netrcItem list
utop # netrcItemList @ [c]
;;
- : netrcItem list =
[{host = "localhost"; username = " root"; password = "admin"}]
utop # let newList: netrcItem list = netrcItemList @ [c];;
val newList : netrcItem list =
[{host = "localhost"; username = " root"; password = "admin"}]
utop # let newList: netrcItem list = netrcItemList @ [a];;
val newList : netrcItem list =
[{host = "www.baidu.com"; username = "admin"; password = "admin"}]
utop # let newList: netrcItem list = newList @ [c];;
val newList : netrcItem list =
[{host = "www.baidu.com"; username = "admin"; password = "admin"};
{host = "localhost"; username = " root"; password = "admin"}]
utop # let newList: netrcItem list = newList @ newList;;
val newList : netrcItem list =
[{host = "www.baidu.com"; username = "admin"; password = "admin"};
{host = "localhost"; username = " root"; password = "admin"};
{host = "www.baidu.com"; username = "admin"; password = "admin"};
{host = "localhost"; username = " root"; password = "admin"}]
基本的初始化语法是
let netrcItemList: netrcItem list = [];;
let 变量名 : 基本数据类型 list = [];
这样是初始化一个空的list
如果你知道里面有几个元素,可以在初始化的时候,就写进去。
否则,我们就可以后面用 @ 符号,把两个List合并进去。
很好的解答了第二个问题,我们怎么把一个新元素,加入到已经有的 List中去呢? 用@ 符号,后面跟 一个只有一个元素的新 List就行了。
两个List会合并成一个
需要注意的是,你可能会问怎么从List中移除元素。对不起。 OCaml默认是数据不可变。
你可以创建一个新的List,然后过滤掉旧的List中不要的元素,把剩余的,塞到新的这个List中去。
分类: 默认 标签: 发布于: 2022-06-27 17:13:01, 更新于: 2022-06-27 17:13:01