gpt4 book ai didi

f# - 具有重复元素的无限序列

转载 作者:行者123 更新时间:2023-12-03 23:25:00 26 4
gpt4 key购买 nike

我需要创建一个无限序列,其中包含无限重复的元素子序列。

[1; 2; 3; 4; 1; 2; 3; 4; 1; 2; 3; 4; ...]

所以我写了这个:
let l = [1; 2; 3; 4]
let s = seq { while true do yield! l }

有没有标准的方法(功能)来做到这一点?

最佳答案

类似于丹尼尔的答案,但将其封装成一个函数,并假装该函数在 Seq 模块中:

module Seq =
let infiniteOf repeatedList =
Seq.initInfinite (fun _ -> repeatedList)
|> Seq.concat

// Tests
let intList = [1; 2; 3; 4]
let charList = ['a'; 'b'; 'c'; 'd']
let objList = [(new System.Object()); (new System.Object()); (new System.Object()); (new System.Object())]
do
Seq.infiniteOf intList |> Seq.take 20 |> Seq.iter (fun item -> printfn "%A" item)
Seq.infiniteOf charList |> Seq.take 20 |> Seq.iter (fun item -> printfn "%A" item)
Seq.infiniteOf objList |> Seq.take 20 |> Seq.iter (fun item -> printfn "%A" item)

关于f# - 具有重复元素的无限序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8919006/

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