F# remove a certain element in an Array

≯℡__Kan透↙ 提交于 2019-12-10 17:17:09

问题


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?

E.g.

remove 2 [| 0 ; 1 ; 2 ; 3 ; 4 |]
val it -> [| 0 ; 1 ; 3 ; 4 |]

UPDATE

Array filter is what I'm looking for. In addition to that, just a bit more specific with my case though.

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?


回答1:


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|]

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))

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 :)



来源:https://stackoverflow.com/questions/19628749/f-remove-a-certain-element-in-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!