Posts Tagged: Functional Programming


3
Nov 08

Yield statements in C#

Yield statements are new to C# 2.0. It largely resembles python’s yield.

Its used to iterate through a set of results returned by a method, but the biggest difference being that the yield statements can maintain the state of that method.

 

It may be a bit confusing, yet pretty simple. Take a look at the following snippet.

Say, if you wanna print numbers between 0 and 50. What will you do ??

for(int i = 1; i < 50 ; i++)
{
  Console.Write(i);  //Just prints i in the screen
}

Really a child’s play. Now if you wanna return the intermediary values to the caller, then ??

Yield assists you in this scenario. Here is how you can do it.

private IEnumerable<int> GetNumbersBetween(int theStart, int theEnd)  //Returns an IEnumerable<int> object that allows iteration using foreach
{
  theStart++;
  while(theStart < theEnd)
  {
    yield return theStart;  //statement that returns the intermediary values
  }


In the main method, you can use,

foreach(integer aNumber in GetNumbersBetween(0, 50))  //iteration is possible because GetNumbersBetween returns IEnumerable<int>
{
  Console.Write(aNumber);  //prints the number
}

You might wonder how the above snippet works. Lets dive in to it. 

First iteration – Here GetNumbersBetween(1,50) will be executed. Unlike the ordinary methods, the GetNumbersBetween() won’t execute / exhaust the entire while loop. As there is a yield statement, it returns 1

Second iteration – Again the GetNumbersBetween(1, 50) will be called. Now since the method returns a yield value, it remembers the previous state. Now internally the value of theStart will be 2. So it returns 2 this time

Third iteration – Again the same method will be called, as usual, the value of theStart will be 3. So it returns 3 this time. This goes until theStart+1 = theEnd

This is how it works. Another confusing snippet for you. If you feel really bad, skip it.

while(true)
{
  yield return 1;  //Not an infinite loop
}

The above is not an infinite loop as this loop is totally controlled by the caller’s loop.

Things that you need to take care while using yield statements

  • Yield can appear only inside a loop (obvious !!) — Check the comments to know more on this 
  • Parameters cannot be ref or out
  • Don’t use yield inside catch or finally blocks (can’t think of a sample problem that covers this scenario)

25
Jul 08

Map, Reduce and Filter

This is my first post here at codelog and all my code snippets for this post would be written in python even though the topic is mostly language agnostic. This is a fairly common feature found popularly in functional programming languages like lisp.

Before we see examples of map-reduce-filter, I would have to explain about lambda functions(which I would be using a lot) – borrowed from lisp.

Lambda Functions

Lambda functions are nameless functions which can be used primarily to define one line functions which need to be passed around. Lambda functions are written using the lambda keyword.

>>> lambda x: x*2
<function <lambda> at 0x81d617c>

This lambda function takes in one argument x and returns twice the input number. This may seems too simple at first, but believe me you can easily write complex stuff using these. You can store these lambda functions and/or pass them around as parameters to other functions.

Map

Map is a function which takes in two arguments – first is a function and second is an array (or list). What it does is simple. It applies the function over all elements of the list and returns another list.

>>> map(lambda x: x*2, [1,2,3,4])
[2, 4, 6, 8]

This doubles all the elements in the list. Here is another example which takes in a list of tuples and adds the two elements in each tuple and creates another list.

>>> map(lambda x: x[0]+x[1], [(1,2), (3,4), (5,6)])
[3, 7, 11]

You can do real cool stuff using these.

Reduce

Reduce also takes in two parameters like map – one is a function and another is a list. But it instead applies the function on two successive parameters from the list. This is useful for adding all the elements in a list.

>>> reduce(lambda x, y: x+y, [1,2,3,4,5,6,7,8,9,10])
55

First it adds 1 and 2, then it adds the result to the next element 3, whose result is added to 4 and so on. This is pretty simple, but you have to keep in mind that the function that you pass in to reduce function takes in 2 parameters.

Filter

Filter is a function which also takes in a method and a list – but returns back another list with all elements which return True when passed to the method. Might seem confusing first – but as the word says it filters out the elements of the list which matches the condition.

>>> filter(lambda x: x%2 == 0, [1,2,3,4,5,6,7,8])
[2, 4, 6, 8]

The lambda function there is very simple. It just checks whether the number is odd or even. It returns True if it is even and False if it is odd. Passing it to a filter function with a list of numbers generates a list with only elements which pass the filter – even numbers.

In Python 3 (which is to be released very soon almost 991 years in advance) there will be slight changes to these four functions. Maybe I should make it as another post in which we will see how we can do the same stuff using list comprehensions – which is the suggested method.