<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Generation 5 &#187; Linq</title>
	<atom:link href="http://gen5.info/q/category/tools/linq/feed/" rel="self" type="application/rss+xml" />
	<link>http://gen5.info/q</link>
	<description>Towards Intelligent Systems</description>
	<lastBuildDate>Fri, 20 Aug 2010 19:43:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>First-Class Functions and Logical Negation in C#</title>
		<link>http://gen5.info/q/2009/03/09/first-class-functions-and-logical-negation-in-c/</link>
		<comments>http://gen5.info/q/2009/03/09/first-class-functions-and-logical-negation-in-c/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 13:50:39 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Dot Net]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=253</guid>
		<description><![CDATA[Introduction Languages such as LISP,  ML,  oCaml F# and Scala have supported first-class functions for a long time.  Functional programming features are gradually diffusing into mainstream languages such as C#,  Javascript and PHP.   In particular,  Lambda expressions,  implicit typing,  and delegate autoboxing have made  C# 3.0 an much more expressive language than it&#8217;s predecssors. In [...]]]></description>
			<content:encoded><![CDATA[<p><img style="margin-right:20px; margin-bottom:20px;" title="negation" src="http://gen5.info/q/wp-content/uploads/2009/03/negation.png" alt="negation" width="99" height="90" align="right" /></p>
<h2>Introduction</h2>
<p>Languages such as LISP,  ML,  oCaml F# and Scala have supported first-class functions for a long time.  Functional programming features are gradually diffusing into mainstream languages such as C#,  Javascript and PHP.   In particular,  Lambda expressions,  implicit typing,  and delegate autoboxing have made  C# 3.0 an much more expressive language than it&#8217;s predecssors.</p>
<p>In this article,  I develop a simple function that acts on functions:  given a boolean function<em> f</em>,  <em>F.Not(f)</em> returns a new boolean function which is the logical negation of <em>f</em>.  (That is,  <em>F.Not(f(x)) == !f(x)</em>).   Although the end function is simple to use,  I had to learn a bit about the details of C# to ge tthe behavior  I wanted &#8212; this article records that experience.<br />
<span id="more-253"></span></p>
<h2>Why?</h2>
<p>I was debugging an application that uses Linq-to-Objects the other day,  and ran into a bit of a pickle.  I had written an expression that would return true if all of the values in a List&lt;String&gt; were valid phone numbers:</p>
<pre>[01] dataColumn.All(Validator.IsValidPhoneNumber);</pre>
<p>I was expecting the list to validate successfully,  but the function was returning false.  Obviously at least one of the values in the function was not validating &#8212; but which one?  I tried using a lambda expression in the immediate window (which lets you type in expression while debugging) to reverse the order of matching:</p>
<pre>[02] dataColumn.Where(s =&gt; !ValidatorIsValidPhoneNumber(x));</pre>
<p>but that gave me the following error message:</p>
<pre>[03] Expression cannot contain lambda expressions</pre>
<p>(The expression compiler used in the immediate window doesn&#8217;t support all of the language features supported by the full C# compiler.)  I was able to answer find the non matching elements using the set difference operator</p>
<pre>[04] dataColumn.Except(dataColumn.Where(Validator.IsValidPhoneNumber).ToList()</pre>
<p>but I wanted an easier and more efficient way &#8212; with a logical negation function,  I could just write</p>
<pre>[05] dataColumn.Except(F.Not(Validator.IsValidPhoneNumber).ToList();</pre>
<h2>Try 1: Extension Method</h2>
<p>I wanted to make the syntax for negation as simple as possible.  I didn&#8217;t want to even have to name a class eliminate the need to name a class,  so I tried the following extension method:</p>
<pre>[06] static class FuncExtensions {
[07]    public static Func&lt;Boolean&gt; Not(this Func&lt;Boolean&gt; innerFunction) {
[08]       return ()  =&gt; innerFunction();
[09]    }
[10]    ...
[11]   }</pre>
<p>I was hoping that,  given a function like</p>
<pre>[12] public static boolean AlwaysTrue() { return true };</pre>
<p>that I could negate the function by writing</p>
<pre>[13] AlwaysTrue.Not()</pre>
<p>Unfortunately,  it doesn&#8217;t work that way:  the extension method can only be called on a delegate of type Func&lt;Boolean&gt;.  Although the compiler will &#8220;autobox&#8221; function references to delegates in many situations,  it doesn&#8217;t do it when you reference an extension method.  I could write</p>
<pre>[14] (Func&lt;Boolean&gt; AlwaysTrue).Not()</pre>
<p>but that&#8217;s not a pretty syntax.   At that point,  I tried another tack.</p>
<h2>Try 2: Static Method</h2>
<p>Next,  I defined a set of negation functions as static methods on a static class:</p>
<pre>[15] public static class F {
[16]    public static Func&lt;Boolean&gt; Not(Func&lt;Boolean&gt; innerFunction) {
[17]       return () =&gt; !innerFunction();
[18]    }
[19]
[20]    public static Func&lt;T1,Boolean&gt; Not&lt;T1&gt;(
[21]       Func&lt;T1,Boolean&gt; innerFunction) {
[22]          return x =&gt;!innerFunction(x);
[23]    }
[24]
[25]    public static Func&lt;T1, T2,Boolean&gt; Not&lt;T1,T2&gt;(
[26]       Func&lt;T1, T2,Boolean&gt; innerFunction) {
[27]          return (x,y) =&gt; !innerFunction(x,y);
[28]    }
[29]
[30]    public static Func&lt;T1, T2, T3, Boolean&gt; Not&lt;T1,T2,T3&gt;(
[31]       Func&lt;T1, T2, T3, Boolean&gt; innerFunction) {
[32]           return (x, y, z) =&gt; !innerFunction(x, y, z);
[33]    }
[34]
[35]    public static Func&lt;T1, T2, T3, T4, Boolean&gt; Not&lt;T1, T2, T3, T4&gt;(
[36]       Func&lt;T1, T2, T3, T4,Boolean&gt; innerFunction) {
[37]          return (x, y, z, a) =&gt; !innerFunction(x, y, z, a);
[38]    }
[39] }</pre>
<p>Now I can write</p>
<pre>[40] F.Not(AlwaysTrue)() // always == false</pre>
<p>or</p>
<pre>[41] Func&lt;int,int,int,int,Boolean&gt; testFunction = (a,b,c,d) =&gt; (a+b)&gt;(c+d)
[42] F.Not(testFunction)(1,2,3,4)</pre>
<p>which is sweet &#8212; the C# compiler now automatically autoboxes the argument to <em>F.Not</em> on line [40].  Note two details of how type inference works here:</p>
<ol>
<li>The compiler automatically infers the type parameters of <em>F.Not()</em> by looking at the arguments of the <em>innerFunction</em>.  If it didn&#8217;t do that,  you&#8217;d need to write
<pre>F.Not&lt;int,int,int,int&gt;(testFunction)(1,2,3,4)</pre>
<p>which would be a lot less fun.</li>
<li>On line [40],  note that the compiler derives the types of the parameters <em>a</em>,<em>b</em>,<em>c</em>, and <em>d</em> using the type declaration on the right hand side (RHS)
<pre>Func&lt;int,int,int,int,Boolean&gt;</pre>
<p>you can&#8217;t write <em>var</em> on the RHS in this situation because that doesn&#8217;t give the compiler information about the parameters and return values of the lambda.</li>
</ol>
<p>Although good things are happening behind the scenes,  there are also two bits of ugliness:</p>
<ol>
<li>I need to implement <em>F.Not()</em> 5 times to support functions with 0 to 4 parameters:  once I&#8217;ve done that,  however,  the compiler automatically resolves the overloading and picks the right version of the function.</li>
<li>The generic <em>Func&lt;&gt;</em> and <em>Action&lt;&gt;</em> delegates support at most 4 parameters.  Although it&#8217;s certainly true that functions with a large number of parameters can be difficult to use and maintain (and should be discouraged),  this is a real limitation.</li>
</ol>
<h2>Extending IEnumerable&lt;T&gt;</h2>
<p>One of the nice things about Linq is that you can extend it by adding new extension methods to IEnumerable.  Not everbody agrees,  but I&#8217;ve always liked the <em>unless()</em> satement in Perl,  which is equivalent to if(!test):</p>
<pre>[42] unless(everything_is_ok()) {
[43]   abort_operation;
[44] }</pre>
<p>A replacement for the <em>Where(predicate)</em> method that negates the <em>predicate</em> function would be convenient my debugging problem:</p>
<p>I built an<em> Unless()</em> extension method that combines <em>Where()</em> with<em> F.Not()</em>:</p>
<pre>[45] public static IEnumerable&lt;T&gt; Unless&lt;T&gt;(
[46]    this IEnumerable&lt;T&gt; input, Func&lt;T, Boolean&gt; fn) {
[47]       return input.Where(F.Not(fn));
[48]     }</pre>
<p>Now I can write</p>
<pre>[49] var list = new List&lt;int&gt;() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
[50] var filtered = list.Unless(i =&gt; i &gt; 3).ToList();</pre>
<p>and get the result</p>
<pre>[51] filtered = { 1,2,3 }</pre>
<h2>Conclusion</h2>
<p>New features in C# 3.0 make it an expressive language for functional programming.  Although the syntax of C# isn&#8217;t quite as sweet as F# or Scala,  a programmer who works with the implicit typing and autoboxing rules of the compiler can create functions that act on functions that are easy to use &#8212; in this article we develop a set of functions that negate boolean functions and apply this to add a new restriction method to IEnumerable&lt;T&gt;.</p>
<p>
<a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fgen5.info%2fq%2f2009%2f03%2f09%2ffirst-class-functions-and-logical-negati"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fgen5.info%2fq%2f2009%2f03%2f09%2ffirst-class-functions-and-logical-negati" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2009/03/09/first-class-functions-and-logical-negation-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Linq To Tell if the Elements of an IEnumerable Are Distinct</title>
		<link>http://gen5.info/q/2009/02/13/using-linq-to-tell-if-the-elements-of-an-ienumerable-are-distinct/</link>
		<comments>http://gen5.info/q/2009/02/13/using-linq-to-tell-if-the-elements-of-an-ienumerable-are-distinct/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 21:15:38 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Dot Net]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=213</guid>
		<description><![CDATA[The Problem I&#8217;ve got an IEnumerable&#60;T&#62; that contains a list of values:  I want to know if all of the values in that field are distinct.  The function should be easy to use a LINQ extension method and,  for bonus points,  simply expressed in LINQ itself One Solution First,  define an extension method 01   public [...]]]></description>
			<content:encoded><![CDATA[<h2><a href="http://gen5.info/q/wp-content/uploads/2009/02/ducks.jpg"><img class="title=&quot;ducks&quot;" src="http://gen5.info/q/wp-content/uploads/2009/02/ducks-300x195.jpg" alt="" width="300" height="195" align="right" /></a>The Problem</h2>
<p>I&#8217;ve got an <em>IEnumerable&lt;T&gt;</em> that contains a list of values:  I want to know if all of the values in that field are distinct.  The function should be easy to use a LINQ extension method and,  for bonus points,  simply expressed in LINQ itself</p>
<h2>One Solution</h2>
<p>First,  define an extension method</p>
<pre>01   public static class IEnumerableExtensions {
02        public static bool AllDistinct&lt;T&gt;(this IEnumerable&lt;T&gt; input) {
03            var count = input.Count();
04            return count == input.Distinct().Count();
05        }
06    }</pre>
<p>When you want to test an <em>IEnumerable&lt;T&gt;</em>,  just write</p>
<pre>07 var isAPotentialPrimaryKey=CandidateColumn.AllDistinct();</pre>
<h2><span id="more-213"></span>Analysis</h2>
<p>This solution is simple and probably scales as well as any solution in the worst case.  However,  it enumerates the <em>IEnumerable&lt;T&gt;</em> twice and does a full scan of the IEnumerable even if non-distinct elements are discovered early in the enumeration.  I could certainly make an implementation that aborts early using a <em>Dictionary&lt;T,bool&gt;</em> to store elements we&#8217;ve seen and a foreach loop,  but I wonder if anyone out there can think of a better pure-Linq solution.</p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2009/02/13/using-linq-to-tell-if-the-elements-of-an-ienumerable-are-distinct/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
