## Sunday, September 13, 2015

### Filter, Guarding You From Fold

"You and your ways; whose wraths to guard you from,"
-- Shakespeare, The Tempest

### Filter

Filter is a lot like a higher order functional bouncer, it prevents undesirable elements from getting into the resulting collection.

A simple example would be a filtering with a function which says if a value is odd or not.

In Dr. Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", he gives the following definition of Filter in terms of Fold:

filter :: (α → Bool) → ([α] → [α])
filter p = fold (λx xs → if p x then x : xs else xs) [ ]

From the definition above, we see that Filter is just Map but with a predicate clause stating if the element should be placed in the resulting collection or not.

Let us look at an example using my name Mike and a function which will check if a character is lower case.

(similar to Map last time)

First Memoize has nothing and X has M.

Next Memoize still has nothing (since M is upper case) and X has i.

Now Memoize has i and X has k.

Then Memoize has i and k while X has e.

Now the Filter will return the result of "ike".

Now what we all came to see, some code examples.

### Clojure

In Clojure we can use the reduce function to move through the collection checking the predicate condition with the if macro guard against undesirable elements.

### C#

With the C# code we'll need to create some type of collection with the seed value which will allow us to add elements to it, we'll use the collection class of List.  We'll simply iterate through the collection using Aggregate and add elements to the memoize List if they pass the predicate clause.

### ECMAScript 2015

In the code above that we'll use the build in JavaScript array method of push to add an element which gets past the guarding predicate function to the array at the end.  We are simply move through the collection we are filtering, pushing elements into the memoize array.

### Fin

There you have it we are able to keep the riffraff elements out using Fold.