Filtering in a sequence


It turns out that when many mechanisms exist to do a task, many things will work. Here is another way to handle the Seq.fold task from yesterday in a much cleaner way. It’s still neat to see all these workable options! Seq has another method, filter, which only returns those elements that return true for the supplied function.

#light

 

open System.Collections.Generic

 

type MyType(propA:string, propB:int) =

    member this.PropA = propA

    member this.PropB = propB

    override this.ToString() = System.String.Format("{0} {1}", this.PropA, this.PropB)

 

let typeSeq =

    [|  new MyType("red", 4);

         new MyType("red", 3);

         new MyType("blue", 3);

         new MyType("blue", 4);

         new MyType("blue", 5);

         |]

 

let filterVals theSeq propAValue =

     theSeq |> Seq.filter(fun (a:MyType) -> a.PropA = propAValue)

 

printfn("%A") (filterVals typeSeq "red")

printfn("%A") (filterVals typeSeq "blue")

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: