gpt4 book ai didi

f# - F# 列表是否持久?

转载 作者:行者123 更新时间:2023-12-01 10:09:26 25 4
gpt4 key购买 nike

我是 F# 的 C# 开发人员,我知道在 .net 中字符串是不可变的。换句话说,每次你修改一个字符串,你都会得到一个新的字符串实例。

对于像我这样的非功能性思维,第一个问题是效率,我知道 C# 可变对象不是持久的。因为字符串操作在大多数应用程序中通常是微不足道的。

我的问题是,F# 列表也是这种情况吗? F# 是否会在更改时克隆每个列表?例如,在过滤列表时,我是否会创建一个包含更少项目的新列表?

更新 : 我不是在比较 .net 字符串和列表。我将字符串命名为不可变对象(immutable对象)的示例,并想知道 F# 是否为它的 List 提供任何特殊处理。

这就是我所说的“persistent”。

最佳答案

我认为 Dustin Campbell's introduction在解释列表不变性方面做得非常出色。

In the functional world, lists are immutable. This means that node sharing is possible because the original lists will never change. Because the first list ends with the empty list, its nodes must be copied in order to point its last node to the second list. After the append operation, our lists look like so:

enter image description here

At this point, the more skeptical among you might be saying, "Well, that's a pretty interesting theory, but can you prove it?"

No problem.

Using the knowledge that F# lists are recursive, we can retrieve the last half of combined (the inner list starting at 4) by taking the tail, of its tail, of its tail. List.tl is the function that F# provides for extracting a list's tail.

> let lastHalf = List.tl (List.tl (List.tl combined));;

val lastHalf : int list

> lastHalf;;

val it : int list = [4; 5; 6]

Finally, because F# is first-class citizen of the .NET Framework, we have full access to all of the base class libraries. So, we can use the Object.ReferenceEquals method to test whether or not lastHalf and second are indeed the same instance.

> System.Object.ReferenceEquals(lastHalf, second);;

val it : bool = true

And there you have it. Believe it or not, appending two immutable lists can actually be faster and more memory efficient than appending mutable lists because fewer nodes have to be copied.

关于f# - F# 列表是否持久?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7003255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com