Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# remove a certain element in an Array

Tags:

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?

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?

like image 457
user2431438 Avatar asked Dec 20 '22 22:12

user2431438


1 Answers

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

like image 71
Gene Belitski Avatar answered Jan 07 '23 07:01

Gene Belitski