Combinatory logic from scratch

November 28th, 2008 by Palard Julien

Cause it’s sooooo sexy, let’s speak about Combinatory Logic !
Rule 1 : You don’t talk about Combinatory Logic
Rule 2 : You don’t talk about Combinatory Logic
Rule 3 : Combinatory Logic is based on Lambda Calculus (see Wikipedia for both)
Rule 4 : A combinator is a Lambda expression taking One and only One combinator as parameter, and returning a Combinator.

As i’m speaking to developers, i’ll use the C# Lambda syntax which is :
(parameter) => statement

Let’s now try our first Combinator, named the Identity Combinator
I = (a) => a;
I named it I, it takes one parameter, localy named ‘a’ and return the parameter as is.

Important Point : How to build combinator taking more than one parameter ?
In C# you should use (a, b, c) => blah blah… but the Rule 4 forbid us to give more than one paraneter, so let’s cheat, imagine :
K = (x) => (y) => x;
K is a Combinator taking x, returning a Combinator taking y and returning x.
so we have K(x) = (y) => x and K(x)(y) = x !
So K take two arguments, x and y, and returns x, but ! K can take only one argument, look at the “K(x) = (y) => x” …

Let’s try with three arguments :

S = (x) => (y) => (z) => x(z)(y(z))
can be called with one, two, or three arguments :
S(x) returns (y) => (z) => x(z)(y(z))
S(x)(y) returns (z) => x(z)(y(z))
s(x)(y)(z) returns x(z)(y(z))

In combinatory logic, they wrote :
I a = a
K x y = x
S x y z = x(z)(y(z))

then they say that in fact, I can be build from S and K :
I = SKK
Ok but what does it means ? where are arguments ? it’s easy :

I = S(K)(K);
S can take 2 parameters “S(x)(y) returns (z) => x(z)(y(z))” ok ? so :
I = (z) => K(z)(K(z))
We have to execute it from left to right, remember, K(a)(b) returns a, so (with a == z and b == K(z)) :
I = (z) => z;

Do you want more ?

Let’s try to understand
B = S (K S) K x y z
B stands for Barbara, from “Syllogism Barbara” (wikipedia says :)
Barbara :
All men are animals.
All animals are mortal.
All men are mortal.

So before all, write B as we understand it, and for readability reasons, i’ll underline parameters for the bolded combinator :
B = S (K(S)) K (x) (y) (z)
We have to execute it from left to right, and we have a S with three parameters :
S(a)(b)(c) returns a(c)(b(c)) :
B = K (S) (x) (K(x)) (y) (z)
From left to right we have a K with two parameters, S and y, it will return S :
B = S (K(x)) (y) (z)
Calling S with three parameters (K(x)), (y), (z) returns (K(x))(z)((y)(z)) :
B = K (x) (z) ((y)(z))
Calling K with two parameters (x), (z), it returns x :
B = x((y)(z))
Which can be simplified to :
B = x(y(z))

It’s time to try it !

delegate C C(C c);
static void Main(string[] args)
{
        C K = (a) => (b) => a;
        C S = (a) => (b) => (c) => a(c)(b(c));
        C I = S(K)(K);
        C B = S(K(S))(K);
}

Download this code: test.cs

It works ! Enjoy ! ! Next time, we will try a Swap combinator, a Combinator reducing to himself and progressing step to the Y Combinator !
[dramatic chord]

The ?? operator aka the Null Coalescing Operator

November 23rd, 2008 by valerian

If are familiar to the use of ternary operators, you must have encountered several situations like this one :

string pageTitle = getTitle() ? getTitle() : "Default Title";

Download this code: bad_situation.cs

You would want to call getTitle() only once, but then you wouldn’t have a simple one-lined initialization of you variable.

Actually there is a simple solution that most langages implements, the null coalescing operator; let’s replace the above C# code with this one :

string pageTitle = getTitle() ?? "Default Title";

Download this code: solution.cs

Now you have the same behaviour, but with only one call to your function. The syntax is simple :

possibly_null_value ?? value_if_null

the “??” operator is implemented in C# since C# 2.0.

You also have it in C and C++ as a GNU extension using the “?:” operator :

string pageTitle = getTitle() ?: "Default Title";

Download this code: solution.cpp

You can get the same behaviour in javascript using the “||” operator :

pageTitle = getTitle() || "Default Title";

Download this code: solution.js

You can read more about this operator here and here

Lazy Loading in php with spl_autload

November 16th, 2008 by Palard Julien

Today, a very short post about the lazy loading in PHP : spl_autoload
I’ll not expose everything about it here, cause it’s already done here :
http://php.net/autoload

Basically, a Lazy Loading allow you to predifine some paths where PHP should seek for classes to include, this allow you to directly instantiate an object without having included its file.

public static function lazyLoad($strClassName)
{
        /* some work to find the file to include mixing strClassName */

        /* include your files here... */
}
spl_autoload_register("lazyLoad");

Download this code: lazy.php

Exclude directories from recursive grep

November 16th, 2008 by Palard Julien

How often are you using grep in subversionned folders like that :

grep -rni foobar . | grep -v .svn

Upgrade to grep 2.5.3 and use (alias it ?)

grep -rni --exclude-dir .svn foobar .

(or … stop using SVN ! ! !)

A JustInTime class

August 30th, 2008 by Palard Julien

I discovered in my code a redundant pattern :
private SomeType _something;
private SomeType something { get { if (_something == null) _something = new SomeType(….); return _something;} }

Usefull in Silverlight, when your Blender always say “Can’t compile ! Strange errors ! but compiles when i comment your WebClient… in ctor of that class…”
So i use it to have members builded the first time they are used, “Just in time”.
/!\ It’s not a Singleton ! i can have others instance of this class new-ing it directly !
/!\ Singleton is Evil // feed the Troll

So i factorized it :

public class Jit<T>
{
  T _instance;
  object[] _ctor_params;

  public Jit(object[] ctor_params)
    {
      _ctor_params = ctor_params;
    }

  public Jit()
    {
    }

  public T create(object[] ctor_params)
    {
      Type[] param_types = ctor_params.Aggregate<object, List<Type>>(
                             new List<Type>(),
                             (List<Type> lt, object o) =>
                               {
                                 lt.Add(o.GetType());
                                 return lt;
                               }).ToArray();
      var ctor = typeof(T).GetConstructor(param_types);
      if (ctor == null)
        throw new Exception(param_types.Aggregate<Type, String>(
                      "No constructor found for " + typeof(T).Name + " taking",
                      (string i, Type t) => { return i + " " + t.Name; }));
      return (T)ctor.Invoke(_ctor_params);
    }

  public T create()
    {
      return (_ctor_params == null)
        ? create(new object[] { })
        : create(_ctor_params);
    }

  public T single()
    {
      if (_instance == null)
        _instance = create();
      return _instance;
    }
}

Download this code: jit.cs

A usage demo :

public class Test
{
  Test(string foo, int bar)
    {
      Console.WriteLine("Test ctor with : " + foo + " and " + bar);
    }

  public void foo()
    {
      Console.WriteLine("bar");
    }
}

public partial class Page : UserControl
{
  public event EventHandler my_event;
  private Jit<Test> test = new Jit<Test>(new object[]{"42", 42});

  public Page()
    {
      InitializeComponent();
      // test is not yet built
      test.single().foo(); // Whill build a Test and call foo()
      test.single().foo(); // Whill call foo on the same Test.
    }
}

Download this code: test.cs

So a :
private SomeType _something;
private SomeType something { get { if (_something == null) _something = new SomeType(….); return _something;} }
became :
private Jit something = new Jit(new object[]{…});

Note the Jit ctor, taking a array of objects, it’s the objects to pass to your ctor’s class (found by reflection using their types)

The art of Events

August 29th, 2008 by Palard Julien

The art of using events to build more independent classes.
/* Found a better example */
Imagine you have a class A and a class B.
A builds B, and B have to communicate with A (call methods … ?)
Some developers (Boooo (I’ve done it … (Booo >> me))) will pass a reference of A to B
“A(){B my_B = new B(this);}” /* Please note the newB private joke */
But what happens when you want an other class, C, who don’t know A to build B ?

So we have to remove the A’s reference in the B ctor.
How B should communicate now ?
- Using Events !
B exposes an event, the builder of B can register on it.
- B can speak to A throwing this event.
- Every class can build a B, and can, if it needs, register on its events, doing whatever he wants when the event is thrown.
B is now fully reusable !

Howto invoke an event via reflection

August 29th, 2008 by Palard Julien

Why this article ? because of this note found on the msdn’s EventInfo page:
“EventInfo is not intended to be used to raise events. An object raises events as dictated by its internal state. ”

Let’s try to raise an event with reflection …
Firstly, let’s search, but not in GetEvent, in GetField :
Type.GetField(String, BindingFlags)
String is the name of the field to get and BindingFlags a bitmask of serarching flags.

Note : To use reflexion, use “System.Reflection”

Let’s try a GetField :

FieldInfo my_event_FieldInfo = this.GetType().GetField("my_event",
                                                       BindingFlags.NonPublic
                                                       | BindingFlags.Instance);

Download this code: 1.cs

Yeah ! it’s not null ! we have now the FieldInfo of our event.
What to do now ? in a FieldInfo, we do not have something like “Fire the event”, huh
But what about “GetValue” ? The “Value” of a “FieldInfo” is the field, so the Value of an event’s FieldInfo isn’t the Event ?
FieldInfo.GetValue(object)
let’s try :

object my_event_by_reflection = my_event_FieldInfo.GetValue(this);

Download this code: 2.cs

Is null … ):
Ohhhh but, while not registered, an event is null … so, let’s try adding a handler…
Is not null ! ! Yeah, so we have our event by reflection now.
————————————————————
Note for those who just said “Why giving an object to GetValue ? And why giving ‘this’” :
1) Take a look at the first “this.getType()”
2) Deduce that it ask the Object to give you its Type, an Object knows its Type.
3) Note that a Type can’t know its Objects …
4) Finally to get a Field of your Object, you ask the Type to give it or your Object, giving a reference to your Object, here : ‘this’;
————————————————————
Now, we have an object, which is the event to call, but, how to call it ?
By reflection ? but … where to search ?
TRICK : Put a breakpoint just after the GetValue, when breaked, add a watch on “my_event_by_reflection.GetType()” and browse it… try my_event_by_reflection.GetType().GetFields() … nothing … try my_event_by_reflection.GetType().GetMethods() … browse it … OH ? What is “Invoke” ?

var my_event_invoke = my_event_type.GetMethod("Invoke");

Download this code: 3.cs

Searching how to call the Invoke … by reflection ? Invoking invoke ? Let’s try :

my_event_invoke.Invoke(my_event_by_reflection, new object[] {this, new EventArgs()} );

Download this code: 4.cs

Invoke take the instance of this type, so the object where GetType where called, and in second parameter an array of object to be given as parameter to the method called, we have to give an object and an eventArgs.
It Works ! here the full working source code :

using System.Reflection;

class Cage_en_metal
{
    public event EventHandler ecraser;

    public Cage_en_metal()
    {
        ecraser += new EventHandler(Libellule_ecraser);
        fireEvent("ecraser", new EventArgs());
    }

    void Libellule_ecraser(object sender, EventArgs e)
    {
        Console.WriteLine("Splatch !");
    }

    void fireEvent(string handler, EventArgs eventArgs)
    {
        var eventInfo = this.GetType().GetField(handler,
                                                BindingFlags.Instance
                                                | BindingFlags.NonPublic);
        if (eventInfo != null)
        {
            var event_member = eventInfo.GetValue(this);
                // Note : If event_member is null, nobody registered to the event, you can't call it.
            if (event_member != null)
                event_member.GetType().GetMethod("Invoke").Invoke(event_member, new object[] { this, eventArgs });
        }
    }
}

Download this code: full.cs

How to make a fake 3D Storyboard with Expression Blend

August 25th, 2008 by Antoine

In this “how to” i will show you how to make a StoryBoard like this:

This is not hard but you have to be famialiar with Blend.

download this video

Silverlight Cursors

August 16th, 2008 by Palard Julien

Today just a little article about Silverlight Cursors, made because there’s no screenshots of cursors on the msdn.
So, first, how to change the cursor when hovering over a UI element ?
- Use the XAML Cursor property of this FrameworkElement :

<Grid x:Name="LayoutRoot" Background="White" Cursor="None"/>

Download this code: cursors.xml

Here is the full list and you can test them :

Then if you want to change the cursor programmatically, use the same property in this way :

using System.Windows.Input;
/*
** Cursors is a Static Class in System.Windows.Input
** defining a set of default mouse pointers
** usable with the Cursor Class
*/
myFrameworkElement.Cursor = Cursors.Arrow;

Download this code: cursors.cs

Finally, if you want to create a custom cursor, the only way i found is to set the cursor to None and load an image, following the cursor programatically (use the MouseMove event).

Silverlight - Password field no longer missing

August 14th, 2008 by Palard Julien

EDIT : There’s now a real PasswordField, our tricks is no longer needed, just read :
http://silverlight.net/blogs/msnow/archive/2008/09/29/silverlight-tip-of-the-day-47-how-to-implement-a-password-box.aspx

Everybody developping in Silverlight knows that there’s no password textbox, and some of us rewrite a UserControl to replace it… yeark !!
There’s a so simple way to create a password textbox :
Use a TextBox and change the font with a home made font in which all characters are ‘*’ …
0 lines of code, do it in XAML

<TextBox FontFamily="password.ttf#Password"/>

Download this code: password.xml

FontFamily can download a file and pick a font from this file, the syntaxe is given “file.ttf#fontname” in my password.ttf the font name is “Password”, with the .ttf have to be in your ClientBin (relatives or absolute URI can be used with nothing, the root directory is checked, so put it in your ClientBin)
According to TimHeuer’s comment, after beta 2, embedding fonts will not work with this way, so watch his video Using custom fonts in silverlight to do it with the right way :)

Dont want to create a .ttf ? download mine. password.ttf