## Sunday, December 16, 2012

### Evens with a Filter

One of the most common "tools" in the functional programming tool belt is the filter.  A filter is typically a function which applied to remove elements a list.

Given the image above, the light green filter called Evens which filters out the member of the list which are not even, in this case out of the list [3; 4; 5; 6] only the members [4; 6] survive the filter.

Note in a language like F# which is immutable the list the filter returns is a new list.

If we want to filter out all of the odd numbers from 1 to 100 we could do the following in F# (using fsi.exe running against Mono).

> let x = [ 1 .. 100 ];;

val x : int list =
[1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 20; 21;
22; 23; 24; 25; 26; 27; 28; 29; 30; 31; 32; 33; 34; 35; 36; 37; 38; 39; 40;
41; 42; 43; 44; 45; 46; 47; 48; 49; 50; 51; 52; 53; 54; 55; 56; 57; 58; 59;
60; 61; 62; 63; 64; 65; 66; 67; 68; 69; 70; 71; 72; 73; 74; 75; 76; 77; 78;
79; 80; 81; 82; 83; 84; 85; 86; 87; 88; 89; 90; 91; 92; 93; 94; 95; 96; 97;
98; 99; 100]

> let evens x =
-   match x with
-   | x when x % 2 = 0 -> true
-   | _ -> false;;

val evens : int -> bool

> x |> List.filter evens
- ;;
val it : int list =
[2; 4; 6; 8; 10; 12; 14; 16; 18; 20; 22; 24; 26; 28; 30; 32; 34; 36; 38; 40;
42; 44; 46; 48; 50; 52; 54; 56; 58; 60; 62; 64; 66; 68; 70; 72; 74; 76; 78;
80; 82; 84; 86; 88; 90; 92; 94; 96; 98; 100]

In our code above we have a list x which has the values 1 through 100 in it.  We likewise have a function called evens which returns true or false based on if the value passed in is divisible by 2.  We conclude with List.filter utilizing our function evens against every member of list x, if evens returns true that element of x is passed to the output list.  Hence with any function which returns a bool, we can encumber that function to a list using List.filter and filter out any undesirable elements.