F#删除数组中的某个元素 [英] F# remove a certain element in an Array
问题描述
我看过F#数组模块,但是似乎没有函数可以从数组中删除某个元素.我只是想知道是否存在执行此操作的功能?
I've looked in F# array module but it seems like there is no function that could remove a certain element from an array. I was just wondering if there exists any function that does so?
例如
remove 2 [| 0 ; 1 ; 2 ; 3 ; 4 |]
val it -> [| 0 ; 1 ; 3 ; 4 |]
更新
我正在寻找数组过滤器.除此之外,我的情况还要具体一点.
Array filter is what I'm looking for. In addition to that, just a bit more specific with my case though.
如果我拥有的数组不是普通类型的数组,而是a特定类的引用的数组.假设我只想删除member.order = 2
的元素,那么谓词将如何?
If the array I have is not a normal type array but an array of a-specific-class's references. Assuming that I want to remove only element whose member.order = 2
, then how would the predicate be?
推荐答案
You may achieve this using F# Array
module function Array.filter, as below:
> [| 0 ; 1 ; 2 ; 3 ; 4 |] |> Array.filter ((<>)2);;
val it : int [] = [|0; 1; 3; 4|]
更新:不难确定应该是lambda.为使其平淡一些,您可以使用另一个单独的函数 Array.choose 获得相同的结果>:
UPDATE: It is not hard to figure out what should be the lambda. To make it a bit less dull, you may obtain the same result with another single function Array.choose:
Array.choose (fun x -> if x.order = 2 then None else Some(x))
还要让我指出,这两个函数都解决了一个稍微不同的 dumb 问题:从数组中删除满足条件的 all 元素.从字面上看,您的问题可以理解为仅删除元素的第一次出现.这样的阅读仍然使您有机会创造性对您的家庭作业做出贡献:)
Also let me point out that both functions address a slightly different dumb question: remove from an array all elements satisfying a condition. Literally your question may be read as removing only first occurrence of the element. Such reading still gives you a chance for creative contribution to your homework :)
这篇关于F#删除数组中的某个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!