List F:使用列表从现有记录创建新记录

List F:使用列表从现有记录创建新记录,list,f#,record,List,F#,Record,假设我有一个定义如下的类型: type State = { intList : int list } let a = { intList = [1; 2; 3; 4] } 以及如下所示的值: type State = { intList : int list } let a = { intList = [1; 2; 3; 4] } 现在假设我想要一个新的值b,a的值末尾加上5。我不知道如何使用with语法来实现它。另外,我也不知道如何获得一个新的状态,例如少了一个元素。with copy

假设我有一个定义如下的类型:

type State = { intList : int list }
let a = { intList = [1; 2; 3; 4] }
以及如下所示的值:

type State = { intList : int list }
let a = { intList = [1; 2; 3; 4] }
现在假设我想要一个新的值b,a的值末尾加上5。我不知道如何使用with语法来实现它。另外,我也不知道如何获得一个新的状态,例如少了一个元素。

with copy and update表达式的语法不允许基于另一条记录的修改属性创建一条记录,只允许复制一些完整的属性并替换其他属性。您可以使用普通记录构造函数:

let a = { intList = [1; 2; 3; 4] }
let b = { intList = a.intList @ [1; 2; 3; 4; 5] }
let c = { intList = List.tail a.intList }
with语法copy and update表达式不允许基于另一条记录的已修改属性创建记录,只允许完整复制某些属性并替换其他属性。您可以使用普通记录构造函数:

let a = { intList = [1; 2; 3; 4] }
let b = { intList = a.intList @ [1; 2; 3; 4; 5] }
let c = { intList = List.tail a.intList }

正如Daniel所说,没有特定的语法可以从要复制和更新的记录中读取属性。但您仍然可以使用普通点表示法访问它:

let a = { intList = [1; 2; 3; 4] }

let b = { a with intList = a.intList @ [5] }

当然,在本例中,with是非常无用的,因为您正在更新所有字段,所以您最好只使用新的记录语法,如Daniel所示。但是,如果记录中也有要从a到b保留的字段,我会这样做。

正如Daniel所说,没有特定的语法可以从要复制和更新的记录中读取属性。但您仍然可以使用普通点表示法访问它:

let a = { intList = [1; 2; 3; 4] }

let b = { a with intList = a.intList @ [5] }
当然,在本例中,with是非常无用的,因为您正在更新所有字段,所以您最好只使用新的记录语法,如Daniel所示。但是如果记录中也有要从a到b保留的字段,我会这样做