我试图附加到下面的列表中:
type Dabg = { trial : int list }
let talc = { trial = [1; 2] }
let Update(i) : Dabg =
let newlist = List.append [(i)] talc.trial
{ trial = newlist }
Update 3
据我所知,Dabg
是不可变的。那么newlist
函数内部trial
到Update
的类型转换实际上只是创建一个副本吗?
答案 0 :(得分:2)
不完全。你实际上并没在这里做任何演员。让我们来看看 所做的代码:
type Dabg = { trial : int list }
这声明了一个新类型,特别是record type,它包含一个名为trial
的名称为int list
的名称 - 值对。
let talc = { trial = [1; 2] }
这将创建记录类型Dagb
的实例,将其trial
的值设置为列表[1; 2]
,并将实例绑定到名称talc
。请注意,talc
,实例,所有名称 - 值对和所有列表都是不可变的 - 您不能使talc
引用不同的对象,更改哪个列表trial
引用或更改该清单的内容。
let Update(i) : Dabg =
let newlist = List.append [(i)] talc.trial
{ trial = newlist }
这定义了一个名为Update
的新函数,它接受一个参数,其类型由类型推断确定(为int
)。它将返回Dabg
类型的值。调用时,它会调用List.append
,这会创建一个新列表,其中包含第一个参数(仅i
)的值,后跟第二个参数的值(列表) talc.trial
)。最后一行是隐式返回值,该函数返回类型为Dabg
的新实例,其中trial
设置为新列表。
Update 3
此行使用参数3调用Update。跟踪执行情况会显示它创建newlist
值[3; 1; 2]
,然后返回类型为Dabg
<的新实例/ strong>试用等于列表[3; 1; 2]
。 未使用此返回值,talc
也未被更改,它仍然引用{ trial = [1; 2] }
。
也许您打算更新trial
的价值?在这种情况下,您可以捕获Update
的返回值并在以后使用它。像:
let newTalc = Update 3
doStuff newTalc
答案 1 :(得分:1)
这是编写它的一种方法。 f
是用于查找要更改的元素的谓词。一旦找到,sub
会转换元素。该函数返回option
,其中Some
包含已更改的列表,None
表示谓词为所有元素返回false。
let replace f sub xs =
let rec finish acc = function
| [] -> acc
| x::xs -> finish (x::acc) xs
let rec search acc = function
| [] -> None
| x::xs ->
if f x then Some(finish ((sub x)::xs) acc)
else search (x::acc) xs
search [] xs
//Usage
let xs = [1;2;3]
let result = xs |> replace ((=) 2) (fun i -> i * 2)
match result with
| Some ys -> printfn "changed list: %A" ys
| None -> printfn "not found"
//> changed list: [1; 4; 3]
答案 2 :(得分:0)
我建议你使用通用的ResizeArray&lt; _&gt; type,在System.Collections.Generic中实现List
你可以像这样使用它:
let customers = new ResizeArray<Customer>()
customers.Add { Name = "some name here"; Id = 40 }
或者像这样:
let numbers = new ResizeArray<int>(seq { for number in [1..10] -> number * number})
使用计算表达式作为构造函数的参数。