gpt4 book ai didi

list - 与 List 相比,F# 序列操作主要慢吗?

转载 作者:行者123 更新时间:2023-12-01 08:15:41 25 4
gpt4 key购买 nike

使用 F# List 和 Seq 合并两个排序的列表/序列。这些值是通过从二级存储器中读取两个文件获得的 - 文件读取的结果存储在两个序列中。假设存储整数用于测试目的,现在尝试合并这些以使用以下代码打印出排序的系列:

let rec printSortedSeq l1 l2 = 
match ( l1, l2) with
| l1,l2 when Seq.isEmpty l1 && Seq.isEmpty l2 -> printfn "";
| l1, l2 when Seq.isEmpty l1 -> printf "%d " (Seq.head l2); printSortedSeq l1 (Seq.skip 1 l2);
| l1, l2 when Seq.isEmpty l2-> printf "%d " (Seq.head l1); printSortedSeq (Seq.skip 1 l1) [];

| l1,l2 -> if Seq.head l1 = Seq.head l2 then printf "%d " (Seq.head l1); printSortedSeq (Seq.skip 1 l1) (Seq.skip 1 l2);
elif Seq.head l1 < Seq.head l2 then printf "%d " (Seq.head l1); printSortedSeq (Seq.skip 1 l1) (Seq.skip 1 l2);
else printf "%d " (Seq.head l2); printSortedSeq (Seq.skip 1 l1) (Seq.skip 1 l2);

该代码最初是为了合并两个排序列表而编写的:
let rec printSortedList l1 l2 = 
match ( l1, l2) with
| h1 :: t1 , h2 :: t2 -> if h1 = h2 then printf "%d " h1; printSortedList t1 t2;
elif h1 < h2 then printf "%d " h1; printSortedList t1 l2;
else printf "%d " h2; printSortedList l1 t2;
| [] , h2 :: t2 -> printf "%d " h2; printSortedList [] t2;
| h1 :: t1, [] -> printf "%d " h1; printSortedList t1 [];
| [], [] -> printfn"";

使用它们的性能非常有利于列表。我在 #time; 后给出计时结果;在 FSI 中的一些试验输入。
let x = [0..2..500];
let y = [1..2..100];

let a = {0..2..500}
let b = {1..2..100}

打印排序列表 x y;;
真实:00:00:00.012,CPU:00:00:00.015

printSortedSeq a b;;
真实:00:00:00.504,CPU:00:00:00.515

问题是 - 有没有办法使用序列使事情更快?因为虽然列表要快得多,但由于提供输入的文件非常大(> 2 GB),它们不适合主内存,所以我从文件中读取值作为惰性序列。在合并之前将它们转换为列表有点违背了整个目的。

最佳答案

Seq.skip 是一种反模式。使用 F# PowerPack 中的 LazyList,或使用枚举器 (GetEnumerator...MoveNext...Current) 有效地遍历 Seq。查看其他类似的问答。

关于list - 与 List 相比,F# 序列操作主要慢吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11201850/

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