替换元素周围范围内的列表中的值

Replacing values in a list in a range around an element

考虑以下因素:

这是一个例程,它接受一个列表、一个阈值和一个宽度,并生成一个数组,其中包含列表中值低于阈值的元素。 如果列表中索引 i 处的值高于阈值,则 i 周围宽度 w 的结果数组中的元素将用 -1 消隐。

let a = [1;4;1;4;3;3;2]
let w = 1
let thresh = 3

let res = Array.copy (a |> List.toArray)
let mutable i = 0
let N = a.Length

while i < N do
    if a.[i] > thresh then
        let lower = if i-w < 0 then 0 else i-w
        let upper = if i+w > N-1 then N-1 else i+w
        for j in lower..upper do
            res.[j] <- -1
    i <- i + 1

这个例子的输出应该是

[|-1; -1; -1; -1; -1; 3; 2|]

虽然这可行,但我想知道这种使用 lists/seqs/arrays 的宽度索引操作是否可以使用 F# 以更实用的方式完成?

将其转化为更实用的方法的关键是从数据转换的角度进行思考。您想要 return 基于特定范围内的值的值,因此首先要做的是将您的数据转换为一组这些范围,然后执行操作。

这个解决方案看起来有点滑稽,因为 Windowed 不对部分 windows 进行操作,因此您需要预先和 post- 附加阈值(或更低)。

let replaceValues lst threshold width =
    seq {
        for n in 1 .. width -> threshold
        yield! lst
        for n in 1 .. width -> threshold
    }
    |> Seq.windowed (width * 2 + 1)
    |> Seq.map (fun x-> 
            if x |> Seq.exists (fun x->x > threshold) then -1
            else x |> Seq.skip width |> Seq.head )