F # Functional Style Serial Filter

I have a sequence of data that I need to filter. This is quite obvious since we have the meaning of Seq.filter . But, my problem is that I need to filter out until the final collection reaches a certain number of elements. I don’t want to perform filtering on all elements, and not do truncate, I want to stop filtering at a time when I no longer need it.

Basically, this is a very simple task in imperative programming - I can do it easily in F #, as it would be done in C #, but I would like to do it in a functional style.

I looked at the Collections.Seq module, but I did not find anything that could help me. In fact, I will need something like filterWhile . Any ideas?

Thank you for your help.

+5
source share
1 answer

You just use Seq.filter and then Seq.take with the number of results you are interested in:

Seq.filter and Seq.take are lazy, and then when seq is forced, it will stop filtering as soon as the result reaches the desired size.

Here is an example using an infinite sequence to check if it really stops filtering:

 Seq.initInfinite id |> Seq.filter (fun x -> x % 2 = 0) |> Seq.take 10 // then if you force the Seq |> Seq.toArray 

And this is a functional style, so you solve the problem in FP languages ​​using a lazy collection, for example, in Haskell, which is a pure FP language, you do the same with lists: take 10 (filter (\x -> mod x 2 == 0) [0..]) .

+9
source

Source: https://habr.com/ru/post/1208116/


All Articles