Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Sequence Filter While in a functional style

I have a sequence of data which I need to filter. This is quite obvious as we have the Seq.filter value. But, my problem is that I need to filter until the resulting collection will reach certain number of items. I do not want to perform the filtering on all items and than make the truncate, I want to stop the filtering in moment when I do not need it any more.

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

I have taken a look on the Collections.Seq module but I have not found anything that will help me. In fact I will need something like filterWhile. Any ideas?

Thank you for help.

like image 632
user2323704 Avatar asked Dec 02 '14 08:12

user2323704


1 Answers

You just use Seq.filter followed by a Seq.take with the number of results you are interested to get:

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

Here is an example, using an infinite sequence to test 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, this is the way you solve the problem in FP languages using a lazy collection, for example in Haskell which is a pure FP language you do it the same way with lists: take 10 (filter (\x -> mod x 2 == 0) [0..]).

like image 141
Gus Avatar answered Sep 17 '22 22:09

Gus