我试图在我的字符串列表中添加一个额外的项目。我首先想到将项目添加到我的列表中::。
let test = ["hello"];;
let newtest = test :: ["world"];;
Run Code Online (Sandbox Code Playgroud)
这给我带来了错误:
let newtest = test :: ["world"];;
-----------------------^^^^^^^
stdin(36,24): error FS0001: This expression was expected to have type
'string list'
but here has type
'string'
Run Code Online (Sandbox Code Playgroud)
它才开始与@. 但是,在创建新列表的几个 SO 问题上,使用了该::方法。为了使用::,我最终创建了一个列表列表,这绝对不是我想要的。
let newtest01 = test :: [["world"]];;
val newtest01 : string list list = [["hello"]; ["world"]]
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下它们之间的区别吗?
在::(“缺点”)运算符前面加上(或consing)项目以现有列表用来创建列表。在@(“追加”)运算符是用来连接两个列表。您应该阅读本主题。
> let test = ["hello"];;
val test : string list = ["hello"]
> let newTest1 = "world" :: test;;
val newTest1 : string list = ["world"; "hello"]
> let newTest2 = test @ ["world"];;
val newTest2 : string list = ["hello"; "world"]
Run Code Online (Sandbox Code Playgroud)