Wednesday, June 25, 2008

C# Puzzle No.9 (beginner)

Consider a delegate declaration which takes a function and returns another function:

delegate Func<int, int> FuncConversionDelegate( Func<int, int> Func );

Your goal is to write a lambda expression defining a converter which would negate values returned by original method:



FuncConversionDelegate Negation = 
    /* 
       replace this with a lambda expression 
       which takes function f and returns function g 
       so that g(x) = -f(x)
    */;

Specifically, you have to replace the commented expression above to a correct definition.


To test the converter, take the identity function:



static Func<int, int> Identity = x => x;

and apply Negation to it:



Negation( Identity )( 5 )
expecting the value of -5 to be returned.

4 comments:

  1. Hello

    Here's my solution
    FuncConversionDelegate NegateLambda3 = func => i => -func(i);

    I wanted to show you entire evolution of this solution (how did I end up with this nice lambda), but blogger says %LT int %GT (generic) is not proper HTML tag.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. One of the ways this could be achieved is using this statement:

    static Func<Func<int, int>, Func<int, int>> Negation = f => j => -f(j) ;

    and then calling Negation(Identity)with an integer as the parameter like it is mentioned as part of the question.

    ReplyDelete