Predicate as functions composition

  • Thread starter Thread starter Marco Segurini
  • Start date Start date
M

Marco Segurini

Hi,

I have written the following code:

// start code
using System;
using System.Collections.Generic;
using System.Text;

namespace MyPredicates
{

static class MyPredicate
{
public static bool Zero(int val)
{
return val == 0;
}
}

class Program
{
static void Main(string[] args)
{
int[] aTmp = new int[] { 0, 0, 33, 0, 0, 22, 0, 0, 12};
foreach(int i in aTmp)
Console.Write(i.ToString() + ',');
Console.WriteLine();

Console.WriteLine(System.Array.FindLastIndex(aTmp,
MyPredicate.Zero));
}
}
}
// end code


Now I'd like to perform a FindLastIndex but with MyPredicate.Zero
negate, something like:

Console.WriteLine(System.Array.FindLastIndex(aTmp, !MyPredicate.Zero));

How may I compound (better if inplace) the logical not and
MyPredicate.Zero to get a valid predicate?

TIA.
Marco.
 
Marco,

You can't really do something like that now in C#. The reason is you
need to pass in a Predicate<int> to the method, and you can't get the result
of the previous predicate into the one you really need (which is
Predicate<bool>).

In C# 3.0, it will be much easier to do, since you will write the
function like this:

Console.WriteLine(System.Array.FindLastIndex(aTmp, i => i == 0));

And when you want to change it, you just do this:

Console.WriteLine(System.Array.FindLastIndex(aTmp, i => i != 0));

Hope this helps.
 
The best I can come up with is something like:

static class MyPredicate
{
public static bool Zero(int val)
{
return val == 0;
}
}

class PredicateNegator<T>
{
Predicate<T> _pred;

public PredicateNegator(Predicate<T> pred)
{
_pred = pred;
}

public bool Negate(T val)
{
return !_pred(val);
}
}

class Program
{
static void Main(string[] args)
{
int[] aTmp = new int[] { 0, 0, 33, 0, 0, 22, 0, 0, 12 };
foreach (int i in aTmp)
Console.Write(i.ToString() + ',');
Console.WriteLine();

Console.WriteLine(System.Array.FindLastIndex(aTmp,
MyPredicate.Zero));
Console.WriteLine(System.Array.FindLastIndex(aTmp, new
PredicateNegator<int>(MyPredicate.Zero).Negate));

Console.ReadLine();
}
}

It's not very elegant - in particlualr it's annoying to have to include the
"<int>" in the "new PredicateNegator<int>" (there may be a way round this
but I'm very new to generics) - but it works.

Chris Jobson
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top