jisakujien – ChalamiuS' Blog https://blog.chalamius.se/ Yet another random blog on the internet Mon, 27 Mar 2017 18:23:38 +0000 en-US hourly 1 https://wordpress.org/?v=7.1 C#: Lambda Expressions https://blog.chalamius.se/2010/01/c-lambda-expressions/ https://blog.chalamius.se/2010/01/c-lambda-expressions/#respond Fri, 08 Jan 2010 22:47:05 +0000 http://blog.chalamius.se/?p=183 Continue reading "C#: Lambda Expressions"

]]>
As a belated follow up to my post on C# Anonymous Methods, let’s look at a closely related feature of the CLS: lambda expressions.  Then let’s use a lambda expression to improve the code example from that earlier article.

Lambda Expressions were introduced in the 3.0 version of the Common Language Specification.  Lambdas are essentially a refinement of anonymous methods.  They allow you to define a block of code which operates on one or more input variables and returns a single result.  Let’s break down a simple lambda example, from the MSDN page on Lambda Expressions:

delegate int del(int i);
static void Main(string[] args)
{
    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}

In this example, a delegate type is defined, del.  Then an instance of the delegate is created using a lambda expression.  Finally, the delegate is executed, and the return value is assigned to the integer variable j.  Let’s ignore everything but the lambda expression itself: x => x * x.

The first character of the expression actually defines a variable named x, which only exists inside the lambda expression.  In the MSDN example, when the lambda is actually executed, x will be assigned the input value of 5.

The => character sequence tells C# that your lambda expression operates on the variable x.  To oversimplify, everything to the left of => is an input variable declaration, and everything on the right is an expression which determines the return value.  In our examples, there will only ever be one input variable.

The x * x character sequence is the actual expression, the bit of code that gets executed.  So we could rewrite down the code above to this:

int x = 5;
int j = x * x;

…and achieve the same result.

Filtering Cars with Lambda Expressions

Returning to our anonymous methods example, we found that the FindAll method of the List<> generic class can take a delegate. The delegate is used to filter which items in the list are returned.

With Anonymous Methods

static void Main(string[] args)
{
    // Create a list of cars meeting criteria by calling the FindAll()
    // method of the List returned by CreateCars().
    List cars = CreateCars().FindAll(delegate(Car candidate)
    {
        // Return whether the car matches our criteria.  FindAll()
        // expects our anonymous method to return a boolean, and
        // the compiler makes sure this is the case.
        return
            candidate.Manufacturer == "Toyota" ||
            candidate.Manufacturer == "Nissan" &&
            candidate.Turbocharged == false;
    });

    foreach(Car car in cars)
    {
        Console.WriteLine(car.ToString());
    }
}

Instead, let’s replace that anonymous method block with a lambda expression.

With Lambda Expressions

static void Main(string[] args)
{
    List cars = CreateCars().FindAll(car =>
        car.Manufacturer == "Toyota" ||
        car.Manufacturer == "Nissan" &&
        car.Turbocharged == false );

    car.Turbocharged = true; // Invalid code, "car" does not exist.
}

In this case, our lambda expression creates the variable car, and then does the same set of conditional tests as the old example. Note that the car variable only exists in the scope of the lambda expression, just like in the anonymous method. For that reason, the second to last line of code would be a compiler error.

So What’s the Difference?

For the purposes of our example, not a whole lot:

  • The input variable and return types are inferred. C# is able to figure out what type car is by looking at where the lambda is used.   The type is actually defined in the CreateCars() method of our earlier example. C# looks at the return type of List<Car> and infers (or deduces) that a lambda expression operating on the FindAll method of that List<Car> would operate on a single input variable of type Car. Note that in the old anonymous methods example, C# was only able to infer the return type.
  • The lambda expression does not need curly braces, since it is a basic expression.
  • The lambda expression does not use the ugly delegate() syntax, thanks to the type inference.

Of course lambda expressions are a bit more complicated than I let on; they can declare multiple input variables, and they can also contain normal procedural code statements (such as calling a method — and that does require using curly braces).

]]>
https://blog.chalamius.se/2010/01/c-lambda-expressions/feed/ 0
C#: Anonymous Methods https://blog.chalamius.se/2009/06/c-anonymous-methods/ https://blog.chalamius.se/2009/06/c-anonymous-methods/#comments Tue, 02 Jun 2009 15:54:39 +0000 http://blog.chalamius.se/?p=146 Continue reading "C#: Anonymous Methods"

]]>
To continue ChalamiuS’ theme of C# goodness, let’s explore a feature of C# introduced in version 2 of the CLS: the anonymous method. Along the way we’ll also encounter Generics and Object Initializers, but they are not the focus of this post.

Anonymous methods and other features of C# 2.0 and 3.0 incorporate paradigms from functional programming and other (relatively) exotic notions. The full implications of this are and the theory behind it are only minimally covered in this post. It should also be noted that in C# 3.0, lambda expressions were introduced, which work similarly to anonymous methods and look a whole lot cooler.

What is an anonymous method?

To answer this question, let’s first define what a named (eg, not anonymous) method is, using Object.ToString() as an example:

  • A method name.
  • A return type. Object.ToString, unsurprisingly, returns a string. Note that void is a type.
  • A parameter list. Object.ToString does not take any parameters.
  • A method body. The default Object.ToString implementation returns the type name.

Without all of these elements, we cannot have a method. Let’s similarly analyze the makeup of an anonymous method:

  • A return type.
  • A parameter list.
  • A method body.

The major difference is, of course, the lack of a method name. Another significant difference not apparent in our comparison is that the return type of parameter list of an anonymous method is declared in a delegate. Any number of anonymous methods may conform to the same delegate. This is a very basic look at anonymous methods. I suggest you read more by people who actually know what they’re talking about.

Why use an anonymous method?

There are any number of reasons to use an anonymous method instead of a regular named method, but my favorite is to help organize small blocks of specialized code. Instead of declaring a very short method and then calling it from only one place in your code, you can put the anonymous method code right inside the method that needs it. Anonymous methods are also a great way of sharing information between blocks of code without having use classes or complex method declarations.

We must be careful to not declare anonymous methods when the code they contain may be used in more than once place. While this can be fixed by refactoring the anonymous method into a named method, it’s best to avoid this pitfall in the first place.

Wait, what?

Instead of drowning in theory and technical arcana, let’s see a (highly contrived) example. In this example, we create a list of cars and print out any car meeting a certain criteria. The code declaring the Car class and filling the list of cars is at the end of this post.

Example without anonymous method

 
static void Main(string[] args)
{
    List cars = CreateCars();

    foreach (Car car in cars)
    {
        if (DoesCarMeetCriteria(car))
            Console.WriteLine(car.ToString());
    }
}

static bool DoesCarMeetCriteria(Car car)
{
    return
        car.Manufacturer == "Toyota" ||
        car.Manufacturer == "Nissan" &&
        car.Turbocharged == false;
}

Example with anonymous method

static void Main(string[] args)
{
    // Create a list of cars meeting criteria by calling the FindAll()
    // method of the List returned by CreateCars().
    List cars = CreateCars().FindAll(delegate(Car candidate)
    {
        // Return whether the car matches our criteria.  FindAll()
        // expects our anonymous method to return a boolean, and
        // the compiler makes sure this is the case.
        return
            candidate.Manufacturer == "Toyota" ||
            candidate.Manufacturer == "Nissan" &&
            candidate.Turbocharged == false;
    });

    foreach(Car car in cars)
    {
        Console.WriteLine(car.ToString());
    }
}

Conclusion

Which do you prefer? I like the anonymous method; while the syntax may seem strange it becomes quite natural after using it a few times. Sadly this example is somewhat weak; using an anonymous method doesn’t really gain us anything. However, showing the true power would touch on language design paradigms and the like, which I am avoiding in this post.

Here’s the rest of the code required to compile and run the example:

The Car class

class Car
{
    public string Manufacturer, Model;
    public bool Turbocharged;

    public override string ToString()
    {
        return String.Format(
            "{0} {1} ({2}Turbo)", 
            Manufacturer, 
            Model, 
            Turbocharged ? "" : "Non-");
    }
}

Creating the Car list

static List CreateCars()
{
    List cars = new List();
    cars.Add(new Car()
    {
        Manufacturer = "Toyota",
        Model = "AE-86 Trueno GT-APEX",
        Turbocharged = false
    });

    cars.Add(new Car()
    {
        Manufacturer = "Toyota",
        Model = "MR2",
        Turbocharged = false
    });

    cars.Add(new Car()
    {
        Manufacturer = "Nissan",
        Model = "180SX",
        Turbocharged = false
    }); // Some models are turbo-charged.

    cars.Add(new Car()
    {
        Manufacturer = "Nissan",
        Model = "Sileighty",
        Turbocharged = true
    });
    return cars;
}
]]>
https://blog.chalamius.se/2009/06/c-anonymous-methods/feed/ 1
Mine Mania https://blog.chalamius.se/2009/02/mine-mania/ https://blog.chalamius.se/2009/02/mine-mania/#respond Sun, 22 Feb 2009 19:38:35 +0000 http://blog.chalamius.se/?p=139 Continue reading "Mine Mania"

]]>

A fanatic is one who can’t change his mind and won’t change the subject.

Sir Winston Leonard Spencer-Churchill, KG, OM, CH, TD, FRS

minesweeper2Not to let our rodent friends have all the fun mine-sweeping, I’ve created a basic C++ ncurses minesweeper game. This diverges some from the theme of Standard Template Library exploration, although it does make use of the std::max and std::min functions.

Good data-structures and prototypes are the cornerstone of any program. Let’s define ours.

#define SIZE 20

typedef struct _position
{
   bool mine;
   bool activated;
} position;
typedef enum _gamestate { init, run, finish } gamestate;
typedef position minefield[SIZE][SIZE];

void draw_field(minefield&,int,int,gamestate);
int get_neighbors(minefield&,int,int);

The main loop implements an extremely simple state machine to control the gameplay stages. It draws the field and processes user input, managing the current location of the cursor. std::min and std::max are used to keep the cursor within bounds.

int main()
{
   initscr(); // Initialize the ncurses screen.
   raw(); // Disable screen buffering.
   noecho(); // Do not show user input.
   keypad(stdscr, TRUE); // Enable directional keys.
   srand(time(NULL));

   minefield field;
   gamestate state = init;
   int xpos = 0, ypos = 0; // Cursor position.

   while(true)
   {
      draw_field(field, xpos, ypos, state);
      move(xpos, ypos*2);
      refresh();
      char c = getch();
      if(init == state)
         state = run;  // We're initialized, advance to next state.
      else if(finish == state)
         break; // We've drawn the finish display, exit.
      switch(c)
      {
      case KEY_UP:
         xpos = std::max(--xpos, 0);
         break;
      case KEY_DOWN:
         xpos = std::min(++xpos, SIZE-1);
         break;
      case KEY_LEFT:
         ypos = std::max(--ypos, 0);
         break;
      case KEY_RIGHT:
         ypos = std::min(++ypos, SIZE-1);
         break;
      case ' ':
         if(field[xpos][ypos].mine == true)
         { // Player hit a mine.
            mvprintw(xpos, ypos*2, "*");
            getch();
            state = finish;
         }
         field[xpos][ypos].activated = true;
         break;
      default:
         state = finish;
      }
   }
   endwin(); // Clean up ncurses window.
   return 0;
}

Drawing the field consists of looping through the map and writing the appropriate symbols to the screen. The ncurses mvprintw function is indispensable for this. I find it helpful to picture a Cartesian plane when looking at this code.

void draw_field(minefield &field, int xpos, int ypos, gamestate state)
{
   for(int x = 0; x < SIZE; x++)
   {
      for(int y = 0; y < SIZE; y++)
      {
         char sym[3] = { '.', ' ', 0 };
         if(init == state)
         {
            field[x][y].mine = (rand()%3 == 0);
            field[x][y].activated = false;
         }
         else if(finish == state)
         {
            sym[0] = field[x][y].mine ? '*' : ' ';
         }
         else if(field[x][y].activated)
            sprintf(&sym[0], "%d", get_neighbors(field, x, y));
         mvprintw(x, y*2, &sym[0]);
      }
   }
   refresh();
}

minesweeper

Notice that the minefield is passed between the functions by reference, indicated by the & prefix in the function prototype (eg, minefield &field). Passing by reference affords us two general advantages: the entire minefield structure is not copied onto the callstack, and we can modify the minefield easily inside functions we have passed it to. In this case, passing by reference also affords us two advantages over pointers: we do not have to use a pointer dereference (* or ->), and we know the minefield will never be NULL or otherwise invalid, so we don’t need to add more logic to handle invalid pointers. Passing by reference, when used appropriately, can result in simpler and more robust programs than those using exclusively pointers.

Use the directional keys to navigate the board, space to test for presence of a mine, and any other key to exit. See the full source for the implementation of the get_neighbors function and some other miscellany.

]]>
https://blog.chalamius.se/2009/02/mine-mania/feed/ 0
Exploding Rats and the C++ Standard Vector https://blog.chalamius.se/2009/02/exploding-rats-and-the-c-standard-vector/ https://blog.chalamius.se/2009/02/exploding-rats-and-the-c-standard-vector/#respond Sat, 21 Feb 2009 17:12:54 +0000 http://blog.chalamius.se/?p=133 Continue reading "Exploding Rats and the C++ Standard Vector"

]]>

Rats are small, cheap, easy to maintain and transport.

Mine-sniffing ratsAs many are aware, land mines present a significant danger in many war-ravaged countries around the world. Numerous innovative techniques have been developed to clear mine fields, rendering the land once again usable and preventing tragic injuries and deaths. A Belgian non-profit organization, APOPO, began a unique program to develop a new method — using Giant Pouched Rats (Nesomyidae Cricetomyinae) to detect mines — dubbed HeroRATS in 2004, and has now deployed the intrepid rodents in Mozambique.

The rats are too light to set off mines, so disappointingly they are not destroyed in the process (sorry, I lied). Instead, the rats are attached to guide lines and trained to scratch at the ground when they sniff out explosives. The mine is then flagged for removal using more appropriate tools.

A zebra is a horse designed by a committee.

I’ll be the first to admit that I am not an expert with the C++ language. In fact, I can use all the practice I can get. I’ve been using the Standard Template Library on and off for almost 3 years now, but know embarrassingly little about it’s full capabilities. In that vein, I will (hopefully) be posting a series of snippets and short programs about the STL. I plan to start simple, and work my way up. Without further ado, the very basics of the STL vector and it’s iterator.

#include <iostream>
#include <vector>
#include <string>

int main()
{
   // Define a vector, which is an array-like container of items.
   // Unlike std::set, vectors can contain the same element any
   // number of times.
   std::vector<std::string> strings;

   // Add some strings to the vector.
   strings.push_back("foo");
   strings.push_back("bar");

   // Insert a string at a specific point in the vector.  Here "baz"
   // is appended to the vector.
   strings.insert(strings.end(), "baz");

   // STL containers (such as vector, set, hash, etc) can be iterated
   // in a manner almost like foreach some in other languages.  First
   // an iterator must be declared.
   std::vector<std::string>::iterator iter = strings.begin();

   // The iterator can be used to access each element of the vector.
   for(;
       iter != strings.end(); /* Don't iterate past the end. */
       iter++) /* iters overload the increment (++) operator. */
   {
      // To retrieve the value at the index represented by the
      // iterator, some more STL syntactical sugar makes it a
      // simply matter of using the dereference (*) operator.
      std::cout << *iter;
      std::cout << std::endl;
   }
}
$ g++ vector.cpp -o vector && ./vector
foo
bar
baz
$

Let me know if I’ve made obvious mistakes, which I tend to do frequently!

]]>
https://blog.chalamius.se/2009/02/exploding-rats-and-the-c-standard-vector/feed/ 0