gpt4 book ai didi

f# - 从数组中删除单个元素

转载 作者:行者123 更新时间:2023-12-02 09:30:46 26 4
gpt4 key购买 nike

我已经研究了几个小时,浏览了我能浏览的每个网站和文档。我不知道如何从数组中删除一个且仅一个元素(在本例中为字符串),同时保持所有重复项完好无损。

确实找到了方法,但是,这绝对是残暴的:

let remItem gs item = 
if (chkItem gs item) then
let mutable fr = [| |] //temporary array
let mutable don = false //check if we found the element
for i in gs.inventory do
if not (i = item) && don then
fr <- (Array.append fr [|i|])
//add to the temp array until we find our item
elif i = item && don = false then don <- true
//we found it, skip just once so it doesn't get added
elif don then fr <- (Array.append fr [|i|])
//now just add everything else to the temp array
{ gs with inventory = fr }
else gs

我写了这个,但我几乎不知道它是如何工作的。 告诉我有更好的方法来做到这一点。我知道不需要可变变量,但我已经编写了十几个看起来同样可怕的纯函数,并得出结论,这是我能做的最好的事情。我已经尝试了很多 Array.* 递归函数,但我似乎也无法使其中任何一个符合我的要求。我只是想知道是否有可能在 F# 中简洁而纯粹地完成此操作。

最佳答案

我认为最简单的方法是首先查找索引(毕竟它是一个数组),然后将其删除 - (我认为)这是性能和纯粹性之间的一个很好的折衷 - 这是一个纯粹的操作但你没有进行太多的复制操作:

let remove x (xs : 'a array) =
match Array.tryFindIndex ((=) x) xs with
| Some 0 -> xs.[1..]
| Some i -> Array.append xs.[..i-1] xs.[i+1..]
| None -> xs

请注意,您必须注意它是第一个索引,因为 xs.[..(-1)] 会抛出异常(而其他边缘情况则可以):

> remove 0 [|1..10|];;
val it : int [] = [|1; 2; 3; 4; 5; 6; 7; 8; 9; 10|]
> remove 1 [|1..10|];;
val it : int [] = [|2; 3; 4; 5; 6; 7; 8; 9; 10|]
> remove 3 [|1..10|];;
val it : int [] = [|1; 2; 4; 5; 6; 7; 8; 9; 10|]
> remove 9 [|1..10|];;
val it : int [] = [|1; 2; 3; 4; 5; 6; 7; 8; 10|]
> remove 10 [|1..10|];;
val it : int [] = [|1; 2; 3; 4; 5; 6; 7; 8; 9|]
> remove 11 [|1..10|];;
val it : int [] = [|1; 2; 3; 4; 5; 6; 7; 8; 9; 10|]

如果您需要更高的性能,您可以创建一个空数组并使用更命令式的样式来复制部件:

let remove x (xs : 'a array) =
match Array.tryFindIndex ((=) x) xs with
| Some i ->
let res = Array.zeroCreate (xs.Length-1)
if i >= 1 then
System.Array.Copy(xs,0,res,0,i)
if i+1 < xs.Length then
System.Array.Copy(xs,i+1,res,i,xs.Length-i-1)
res
| None -> xs

关于f# - 从数组中删除单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33274107/

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