Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# pattern filtering

Tags:

f#

Can someone please give me advice on how to filter out a list of lists when it contains a certain number. For example, if the sub-lists contain 2 then I want the third value.

let p = [ [0;2;1]; [7;2;5]; [8;2; 10]; [44; 33; 9]]
//Filtered List: [1;5;10]
let q = p |> List.filter(fun((x,y):int List)  (List.item 2 x) = 1,  (List.item 3 y))

Above is my code so far. I know its wrong but can't seem to figure it out in code.

like image 744
Shiro Pie Avatar asked May 08 '26 09:05

Shiro Pie


1 Answers

s952163's answer is correct, however, List.choose would be better.

p
|> List.choose (fun list ->
  if List.contains 2 list then
    Some list.[2]
  else
    None
)

With the solution above you only iterate through the list once.

like image 140
József Uri Avatar answered May 11 '26 01:05

József Uri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!