Saturday, October 19, 2013

A Foo Bar Example I Actually Like

I really, really dislike "foo bar" examples. You can read about my worst foo bar experience here: Session Spotlight: IEnumerable, ISaveable, IDontGetIt.

There's 2 primary reason for this. First, I like real-world examples -- something that I can hold on to. "Foo" doesn't mean anything (that's why it's used), so I have a difficult time relating. The second reason is that "foo bar" makes me think of FUBAR (which may actually be appropriate).

Higher Order Functions
As recently noted, I'm learning functional programming with Haskell. It is a different way of thinking, and I'm starting to get the hang of it. I'm reading about higher order functions right now.

A higher order function is a function that takes another function as a parameter. To relate this to the C# world, this is similar to passing a predicate/delegate/lambda as a parameter to a method (like a LINQ method such as "Where"). But this seems more natural in a functional language.

Here's the function that we need: zipWith':


The scary thing is that I actually understand this. It uses a combination of a higher order function, recursion, pattern matching, and list heads/tails.

Rather than explain this line by line, let's look at an example of using this method:


This shows a call to zipWith that has the "+" function as the first parameter, then we have 2 lists of integers. This method will apply the function to the items of each list. So, it will add ("+") the first item of the first list ("1") to the first item of the second list ("4"). Then it will add the second items of each list, and so on.

Here's the output:


This is a list consisting of 1+4, 2+5, and 3+6. The 7 at the end of the second list is ignored since there is no corresponding item in the first list.

Foo Bar Baz
So, you've made it this far. Here's the foo bar example:


This has a different function: ++. This will concatenate 2 lists together. Since strings are lists of characters, this will concatenate the strings from the first list with the strings from the second list.

Here's the output:



The sin of using a foo bar example has been forgiven.

Happy Coding!

No comments:

Post a Comment