首页 > 解决方案 > f#中的`::`和`@`有什么区别?

问题描述

我试图在我的字符串列表中添加一个额外的项目。我首先想到将项目添加到我的列表中::

let test = ["hello"];;
let newtest = test :: ["world"];;

这给我带来了错误:

  let newtest = test :: ["world"];;
  -----------------------^^^^^^^

stdin(36,24): error FS0001: This expression was expected to have type
    'string list'    
but here has type
    'string'

它才开始与@. 但是,在创建新列表的几个 SO 问题上,使用了该::方法。为了使用::,我最终创建了一个列表列表,这绝对不是我想要的。

let newtest01 = test :: [["world"]];;
val newtest01 : string list list = [["hello"]; ["world"]]

有人可以解释一下它们之间的区别吗?

标签: listf#

解决方案


( ::'cons') 运算符用于通过在现有列表前添加(或约束)项目来构建列表。( @'append') 运算符用于连接两个列表。你应该阅读这个主题

> 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"]

推荐阅读