Seq.map (-6ren">
gpt4 book ai didi

f# - 在 F# 中,如何在不重新评估 seq 的情况下获取 seq 的头/尾

转载 作者:行者123 更新时间:2023-12-05 01:00:41 24 4
gpt4 key购买 nike

我正在读取一个文件,我想对第一行做一些事情,对所有其他行做一些其他事情

let lines = System.IO.File.ReadLines "filename.txt" |> Seq.map (fun r -> r.Trim())

let head = Seq.head lines
let tail = Seq.tail lines

```

问题:对 tail 的调用失败,因为 TextReader已经关闭。
这意味着 Seq被评估两次:一次得到 head一次获得 tail .

如何在保持 Seq 的同时获得 firstLine 和 lastLines并且不重新评估 Seq ?

签名可以是,例如:
let fn: ('a -> Seq<'a> -> b) -> Seq<'a> -> b

最佳答案

最简单的方法可能就是使用 Seq.cache 包裹你的lines顺序:

let lines =
System.IO.File.ReadLines "filename.txt"
|> Seq.map (fun r -> r.Trim())
|> Seq.cache

文档中的注意事项:

This result sequence will have the same elements as the input sequence. The result can be enumerated multiple times. The input sequence is enumerated at most once and only as far as is necessary. Caching a sequence is typically useful when repeatedly evaluating items in the original sequence is computationally expensive or if iterating the sequence causes side-effects that the user does not want to be repeated multiple times.

关于f# - 在 F# 中,如何在不重新评估 seq 的情况下获取 seq 的头/尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51900023/

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