<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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/"
	>

<channel>
	<title>lazy-evaluation &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/lazy-evaluation/</link>
	<description>Feed of posts on WordPress.com tagged "lazy-evaluation"</description>
	<pubDate>Wed, 19 Jun 2013 09:38:50 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[My New Mantra: Modularity is the Key to Successful Programming]]></title>
<link>http://rogercostello.wordpress.com/2013/03/08/my-new-mantra-modularity-is-the-key-to-successful-programming/</link>
<pubDate>Fri, 08 Mar 2013 19:17:18 +0000</pubDate>
<dc:creator>Roger Costello</dc:creator>
<guid>http://rogercostello.wordpress.com/2013/03/08/my-new-mantra-modularity-is-the-key-to-successful-programming/</guid>
<description><![CDATA[Modularity is the key to successful programming. [John Hughes] Lazy evaluation is perhaps the most p]]></description>
<content:encoded><![CDATA[<p><i>Modularity is the key to successful programming.</i> [<a href="http://www.xfront.com/Haskell/Why-Functional-Programming-Matters.pdf">John Hughes</a>]</p>
<p>Lazy evaluation is perhaps the most powerful tool for modularization in the functional programmer&#8217;s repertoire. Consider …</p>
<p>Most functional programming languages have a function called &#8220;repeat&#8221; which generates an infinite list; its argument is used as the value of the list. For example, this generates an infinite list of 3:</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="font-family:courier;">repeat 3&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;returns [3, 3, 3, …]</span></p>
<p>Also provided by most functional programming languages is a function called &#8220;take&#8221; which has two arguments, an integer N and a list. The function &#8220;take&#8221; returns the first N values of the list.</p>
<p>&#8220;take&#8221; can be <i>composed</i> with &#8220;repeat&#8221; to obtain a pruned list of values. The following returns the first 5 values of an infinite list:</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="font-family:courier;">take 5 . repeat</span></p>
<p>Function composition is denoted by the dot ( . )</p>
<p>Applying that composed function to 3 results in a list of five 3&#8242;s:</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="font-family:courier;">(take 5 . repeat) 3&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;returns [3, 3, 3, 3, 3]</span></p>
<p>It is lazy evaluation that allows us to modularize the pruning problem in this way. The &#8220;repeat&#8221; function is evaluated lazily – only as many values as requested are generated. So lazy evaluation is very efficient. Without lazy evaluation we would have to fold these two functions together into one function which only constructs the first five values.</p>
<p>Here&#8217;s another example. We can define the set of even numbers by enumerating all positive numbers [1..] and multiplying each by 2:</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="font-family:courier;">evens = [x * 2 &#124; x &#60;- [1..]]</span></p>
<p>That is, of course, an infinite list. However, lazy evaluation will compute only as many as needed. Let&#8217;s take the first 5 evens:</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="font-family:courier;">take 5 evens&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;returns [2, 4, 6, 8, 10]</span></p>
<p>One more example. The example comes from the field of Artificial Intelligence. A decision tree is generated. It could be a decision tree for medical diagnosis or a decision tree for chess moves or a decision tree for something else. The decision tree is potentially infinite. Without lazy evaluation, processing may never terminate. Rather than exploring a potentially infinite space we prune the tree to a depth of, say, 5 levels:</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="font-family:courier;">prune 5 . decisiontree</span></p>
<p>decisiontree is a function that generates the tree. prune 5 chops off any levels of the tree beyond 5 levels deep. <i>We can make improvements by tinkering with each part.</i> Without lazy evaluation we would have to fold these two functions into one function which only constructed the first five levels of the tree. That is a significant reduction in modularity.</p>
<p><strong>Lesson Learned</strong>: Want to have successful software? Then you need to learn how to take advantage of the enhanced modularity that lazy evaluation provides. And, of course, you need to use a programming language that supports lazy evaluation.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Yielding results - the process involved with generating generators]]></title>
<link>http://blog.alxandr.me/2012/10/10/yielding-results-the-process-involved-with-generating-generators/</link>
<pubDate>Wed, 10 Oct 2012 14:51:32 +0000</pubDate>
<dc:creator>Aleksander Heintz</dc:creator>
<guid>http://blog.alxandr.me/2012/10/10/yielding-results-the-process-involved-with-generating-generators/</guid>
<description><![CDATA[One of the nice things about the language C# is it&#8217;s ability to create generators with the yie]]></description>
<content:encoded><![CDATA[<p>One of the nice things about the language C# is it&#8217;s ability to create generators with the yield keyword. Now, for those of you who do not know what I&#8217;m talking about, take a look at the following code:</p>
<pre class="brush: csharp; title: ; notranslate" title="">
public IEnumerable&#60;int&#62; MakeGenerator(int num0)
{
    yield return num0;    

    int i = 0;
    Console.WriteLine(&#34;yield 0&#34;);
    yield return 0;
    try
    {
        i += 1;
        Console.WriteLine(&#34;yield 1&#34;);
        yield return i;
    }
    catch {}
    Console.WriteLine(&#34;end&#34;);
}
</pre>
<p>The code above will return a IEnumerable, and will not do anything else, until the IEnumerable is used. In other words, if I invoke MakeGenerator, none of the code I wrote will actually be run. Now, this might sound completely ridiculous, but I assure you, there is a good reason for this. To explain it as simple as possible, consider the following code, what would you guess the output to be like?</p>
<pre class="brush: csharp; title: ; notranslate" title="">
foreach(int num in MakeGenerator(5))
{
    Console.WriteLine(&#34;Got &#34; + num);
}
</pre>
<p>The answer might surprise you. If you run the code above, you will get 6 lines of output, in the following order:</p>
<pre class="brush: plain; title: ; notranslate" title="">
Got 5
yield 0
Got 0
yield 1
Got 1
end
</pre>
<p>The reason for this is that first when GetNext on the enumerator which the foreach-loop get&#8217;s from the IEnumerable is called, the code in the MakeGenerator-method is actually run. However, as you can see, not all of it is run. When we hit any of the yield-statements, the method is returned from. Now, this is a construct that&#8217;s actually quite useful in a lot of cases, cause for once, it enables lazy evaluation of your code over enumerables. LINQ for once, relies heavily on this (note; I do not know if LINQ uses yields or customarily created enumerators, but they both facilitate lazy evaluation over enumerables). For instance, if you have a list of a million elements (called myList), and you do myList.Select(CpuHeavyMethod), this will not fry your CPU into oblivion, rather, it will not run the CpuHeavyMethod at all! First when you actually have need for an element passed through the CpuHeavyMethod it will be called.</p>
<p>For those of you who still do not know what a generator is, you can learn more here: <a href="http://en.wikipedia.org/wiki/Generator_(computer_programming)" target="_blank">http://en.wikipedia.org/wiki/Generator_(computer_programming)</a></p>
<h2>Creating generators</h2>
<p>Now that (hopefully) all of you have a basic understanding of what generators are, and how they work, let&#8217;s look at how to make them. In other words, let&#8217;s look at what the compiler does with the yield keyword. Now, before I start, I&#8217;d just like to say that this is most likely different from language to language, and this may or may not be the way C# handles compiling generators (I&#8217;ve not looked at how the C#/mono compiler solves the problem, what I&#8217;ve read is how the IronPython compiler/interpreter does it. However, I&#8217;ve also changed that a bit to simplify).</p>
<p>As it turns out, generating generators is actually rather simple, there are just a few things you have to look out for:</p>
<ul>
<li>Try statements (with or without finally) must be handled separately (and with a little bit of caution).</li>
<li>There cannot be yield-statements in catch or finally-blocks.</li>
</ul>
<p>Note: these are rules I&#8217;ve set for the generator I create. It may be possible to have yields in both catch and finally in C#, though it would require further rewriting of the method, and will not be discussed in this article.</p>
<p>The first thing we need to do (in C# anyways) is to create 2 classes. One for the IEnumerable, and one for the IEnumerator. Also, these two classes will be nested, to enable the inner one to access the outer one&#8217;s private variables.</p>
<p>Let&#8217;s start with these two completely empty classes (save for the interface-implementations, and _state and _current values which I&#8217;ll get back to later).</p>
<pre class="brush: csharp; title: ; notranslate" title="">
class MakeGenerator_Generator : IEnumerable&#60;int&#62;
{
	IEnumerator&#60;int&#62; IEnumerable&#60;int&#62;.GetEnumerator()
	{
		return new MakeGenerator_Enumerator(this);
	}

	IEnumerator IEnumerable.GetEnumerator()
	{
		return new MakeGenerator_Enumerator(this);
	}

	class MakeGenerator_Enumerator : IEnumerator&#60;int&#62;
	{
		private readonly MakeGenerator_Generator _gen;
		private int _state = -1;
		private int _current;

		public MakeGenerator_Enumerator(MakeGenerator_Generator gen)
		{
			_gen = gen;
		}

		int IEnumerator&#60;int&#62;.Current
		{
			get { return _current; }
		}

		object IEnumerator.Current
		{
			get { return _current; }
		}

		bool IEnumerator.MoveNext()
		{
			throw new NotImplementedException();
		}

		void IEnumerator.Reset()
		{
			throw new NotImplementedException();
		}

		void IDisposable.Dispose()
		{
			throw new NotImplementedException();
		}
	}
}
</pre>
<p>The first thing we need to do is to take all the method-parameters given to the MakeGenerator method and make them class-level readonly members of the Generator-class. Then we need to add a constructor that takes the same number of arguments, and saves them to the class members.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
class MakeGenerator_Generator : IEnumerable&#60;int&#62;
{
	readonly int param_num0;

	public MakeGenerator_Generator(int num0)
	{
		param_num0 = num0;
	}
</pre>
<p>Then we need to copy those to private members of the Enumerator-class during it&#8217;s Reset() call, and lastly we need to call Reset() from the constructor like this:</p>
<pre class="brush: csharp; title: ; notranslate" title="">
	class MakeGenerator_Enumerator : IEnumerator&#60;int&#62;
	{
		private readonly MakeGenerator_Generator _gen;
		private int _state;
		private int _current;
		private int val_num0;

		public MakeGenerator_Enumerator(MakeGenerator_Generator gen)
		{
			_gen = gen;
			((IEnumerator)this).Reset();
		}

		void IEnumerator.Reset()
		{
			val_num0 = _gen.param_num0;
		}

</pre>
<p>The next thing we need to do is to copy the entire content of the original method into the MoveNext method of the Enumerator (note, this will make for invalid code, but we&#8217;ll fix that in a bit). The result should look like this:</p>
<pre class="brush: csharp; title: ; notranslate" title="">
		bool IEnumerator.MoveNext()
		{
			yield return num0;

			int i = 0;
			Console.WriteLine(&#34;yield 0&#34;);
			yield return 0;
			try
			{
				i += 1;
				Console.WriteLine(&#34;yield 1&#34;);
				yield return i;
			}
			catch {}
			Console.WriteLine(&#34;end&#34;);
		}
</pre>
<p>Now that we have the base-foundation of the generator, we can start editing the original code to make it work as a generator (in other words, rewrite it to a proper MoveNext method).<br />
What needs to be done in the MoveNext methods is two things for startes. First; all variables needs to be hoisted out to class-level variables, and second, we need to enumerate the yield-statements (starting from 1). Than you change the nth yield-statement into this:</p>
<pre class="brush: csharp; title: ; notranslate" title="">
_state = &#60;n&#62;;
_current = &#60;yield_value&#62;;
return;
yield_label_&#60;n&#62;:
</pre>
<p>The result of doing those two actions looks like this:</p>
<pre class="brush: csharp; title: ; notranslate" title="">
		bool IEnumerator.MoveNext()
		{
			_state = 1;
			_current = val_num0;
			return;
			yield_label_1:;

			val_i = 0;
			Console.WriteLine(&#34;yield 0&#34;);

			_state = 2;
			_current = 0;
			return;
			yield_label_2:;

			try
			{
				val_i += 1;
				Console.WriteLine(&#34;yield 1&#34;);

				_state = 3;
				_current = i;
				return;
				yield_label_3:;
			}
			catch {}
			Console.WriteLine(&#34;end&#34;);
		}
</pre>
<p>For those of you who have never seen a label in C# before, this code might look a bit confusing. A label in C# is created by typing a name followed by a colon, like &#8220;yield_label_0:&#8221; The use of a label is with goto, where you jump to a label. The reason I&#8217;ve added a semicolon after the label, is simply to add an empty statement you jump to. This would not strictly be necessary, however, if I do not the yield_label_3 would be invalid (as you cannot have a label that goes &#8220;off a cliff&#8221;, ie. out of a method, if, while, block, etc.). The next part is simply to add a switch over the state in the beginning of the MoveNext method, that jumps to the right continuation. Also, we need to add the final state (_state == 0, finnished). The result looks like this:</p>
<pre class="brush: csharp; title: ; notranslate" title="">
		bool IEnumerator.MoveNext()
		{
			switch(_state)
			{
				case 1: goto yield_label_1;
				case 2: goto yield_label_2;
				case 3: goto yield_label_3;
				case 0: goto yield_label_0;
			}

			_state = 1;
			_current = val_num0;
			return;
			yield_label_1:;

			val_i = 0;
			Console.WriteLine(&#34;yield 0&#34;);

			_state = 2;
			_current = 0;
			return;
			yield_label_2:;

			try
			{
				val_i += 1;
				Console.WriteLine(&#34;yield 1&#34;);

				_state = 3;
				_current = i;
				return;
				yield_label_3:;
			}
			catch {}
			Console.WriteLine(&#34;end&#34;);

			_state = 0;
			yield_label_0:;
			return _state != 0;
		}
</pre>
<p>This is basically a working generator. The two first values would work just fine if we simply left it like this (and removed the try), however, since we do have a try (cause I wanted to show how to solve this), this is what we do.</p>
<ol>
<li>Start with the outermost try (only do this if the try contain yield-statements).</li>
<li>Create a new label in front of the try.</li>
<li>Rewrite all goto-statements that point to a yield inside the try so they point to the new label instead.</li>
<li>Rewrite the try so it jumps based on state.</li>
</ol>
<p>In other words, it goes like this:</p>
<pre class="brush: csharp; title: ; notranslate" title="">
switch(_state)
{
	case 1: goto yield_label_1;
	case 2: goto yield_label_2;
	case 3: goto try_label_1; // 3. Rewrite goto-statement to point to start of try
	case 0: goto yield_label_0;
}

_state = 1;
_current = val_num0;
return;
yield_label_1:;

val_i = 0;
Console.WriteLine(&#34;yield 0&#34;);

_state = 2;
_current = 0;
return;
yield_label_2:;

try_label_1:; // 2. create label in front of the try
try
{
	switch(_state) // 4. Rewrite the try so it jumps based on state
	{
		case 3: goto yield_label_3;
	}

	val_i += 1;
	Console.WriteLine(&#34;yield 1&#34;);

	_state = 3;
	_current = i;
	return;
	yield_label_3:;
}
catch {}
Console.WriteLine(&#34;end&#34;);

_state = 0;
yield_label_0:;
return _state != 0;
</pre>
<p>And there you have it. We&#8217;ve made ourselves a generator. The only thing that needs to be fixed now is to remove the NotImplementedException inside the Dispose-method. What you should probably do inside the Dispose-method is set the _gen-variable to null, and check for it being null in both MoveNext and Current (and if it is, throw a InvalidOperationException because it&#8217;s already disposed), however, I&#8217;ll leave that up to you guys. Also, I was planing on showing how to create Generators with the DLR, though it seems this post became longer than I planned it, and if I were to start explaining the DLR stuff now, I&#8217;d probably more than double the length, so that will come later. I hope this made it easier to understand how generators work, and what the compiler does with them.</p>
<p>Until next time.<br />
- Alxandr</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Count &gt; 0 vs Any()]]></title>
<link>http://alottolearndotnet.wordpress.com/2012/10/08/count-0-vs-any/</link>
<pubDate>Mon, 08 Oct 2012 07:32:11 +0000</pubDate>
<dc:creator>Rick Neeft</dc:creator>
<guid>http://alottolearndotnet.wordpress.com/2012/10/08/count-0-vs-any/</guid>
<description><![CDATA[What I see many developer are doing, and what I did in the past, is using Count &gt; 0 to determine]]></description>
<content:encoded><![CDATA[<p>What I see many developer are doing, and what I did in the past, is using Count &#62; 0 to determine whenever a collection has an item. When you would like to know whenever an items exists in a collection, you have two options:</p>
<ul>
<li>myCollection.Count() &#62; 0</li>
<li>myCollection.Any()</li>
</ul>
<p>Both operations seem to be correct. When an item exist in a list both operations returns true and a Unit test to test whenever it returns true will pass. However it is better not to use the Count method. Especially when using large data sets.</p>
<p><strong>myCollection.Count() &#62; 0<br />
</strong>Intellisense about Count:<em> Returns the number of elements in a sequence</em>.  This means when you use Count() &#62; 0 to check whenever the list contains an item, the list must be filled with items. When using large data sets it first retrieves all the data and then calculates the number of elements.</p>
<p><strong>myCollection.Any()</strong><br />
Intellisense about Any(): <em>Determines whether any element of a sequence satisfies a condition</em>. When using the method Any(), it only needs to know whenever 1 items exists in the list. This is way faster than first counting the numbers of items.</p>
<p>To demonstrate the difference in speed use the following scenario. Create a console application, .net framework 3.5 or higher, and replace the Program.cs code with this code:</p>
<pre class="brush: csharp; title: ; notranslate" title="">
using System;
using System.Linq;
using System.Collections.Generic;

namespace ALotToLearn.CountAny
{
    class Program
    {
        static void Main(string[] args)
        {
            var numbersCount = Numbers();
            var numbersAny = Numbers();

            if (numbersCount.Count() &#62; 0)
                Console.WriteLine(&#34;A number exists in the collection &#34;);

            if (numbersAny.Any())
                Console.WriteLine(&#34;A number exists in the collection &#34;);
        }

        static IEnumerable&#60;int&#62; Numbers()
        {
            yield return 1;
            yield return 2;
            yield return 3;
            yield return 4;
            yield return 5;
            yield return 6;
            yield return 7;
            yield return 8;
        }
    }
}
</pre>
<p>When you run the program it will display &#8220;A number exists in the collection&#8221; twice. Now run the program with a breakpoint at line 11 and step through the code.</p>
<p>The first thing that you will notice is that the Visual Studio doesn’t step into the Numbers() method, when you assign the collection to the variables. This is because the compiler is using <a href="http://en.wikipedia.org/wiki/Lazy_evaluation"><em>lazy evaluation</em></a> for that method. The method, and the results, is only called when we actually need the data. This will decrease the number of calculation while running the application. Please read the <a href="http://en.wikipedia.org/wiki/Lazy_evaluation">Wikipedia page</a> for more information about lazy evaluation.</p>
<p>When you step into line 14 you will notice that the Visual Studio is stepping into the Numbers() method. We now need that data to calculate the numbers. You will see that it stepped over every <a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0(v=vs.100).aspx">yield return</a>. This is because every number is needed to <em>return the number of elements in a sequence</em>. Of course the Count is higher than 0, it returns true and a Unit test, when we had created one will pass.</p>
<p>Now step into line 17. You will now notice that Visual Studio is stepping into the Numbers() method but at the first yield return it will stop calling the method. This is because the Any() method has found an item that <em>satisfied a condition,</em> returns true and… you know the rest<em>.</em></p>
<p>This example did not show the big impact it can have, but imagine you connecting to a potentially large database and need to know a particular table has an item.</p>
<p>Happy coding!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[惰性求值]]></title>
<link>http://legendism.wordpress.com/2012/08/17/%e6%83%b0%e6%80%a7%e6%b1%82%e5%80%bc/</link>
<pubDate>Fri, 17 Aug 2012 08:52:05 +0000</pubDate>
<dc:creator>legendsland</dc:creator>
<guid>http://legendism.wordpress.com/2012/08/17/%e6%83%b0%e6%80%a7%e6%b1%82%e5%80%bc/</guid>
<description><![CDATA[惰性求值是函数式编程里面非常常见并且非常有用的一种求值策略。正如名字所暗示的：尽可能将求值计算拖到最后不得不算的时候。高阶函数和惰性求值可以视为函数式编程的左右使，为程序的模块提供了非常强大的方法。]]></description>
<content:encoded><![CDATA[<div style="font-family:'Microsoft Yahei', Georgia, serif;font-size:14px;"> <a name="preamble"></a>
<p>惰性求值是函数式编程里面非常常见并且非常有用的一种<a href="http://en.wikipedia.org/wiki/Evaluation_strategy">求值策略</a>。正如名字所暗示的：尽可能将求值计算拖到最后不得不算的时候。高阶函数和惰性求值可以视为函数式编程的<a href="http://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf">左右使</a>，为程序的模块提供了非常强大的方法。</p>
<p>这篇博客使用惰性求值来 <strong>表达</strong> <a href="http://www.sosmath.com/calculus/diff/der07/der07.html">牛顿平方根算法</a>。数值算法的思路一般就是采用无穷逼近的方法得到任意精确的结果（但不是准确的结果），基本思路如下：</p>
<p>如果 a 是 n 的平方根，那么 a^2 = n<br /> 如果 a0 近似 n 的平方根，由这个近似值可以推测更近似的下一个值： a1 = (a0 + n/a0) / 2<br /> 类似的： a2 = (a1 + n/a1) / 2<br /> &#8230;<br /> an+1 = (an + n/an) / 2</p>
<p>这样我们能得到一个无穷序列： [a0 a1 a2 &#8230; an &#8230; ]，越是后面的项，（可以证明当a0取值合理的时候）越接近 n 的平方根。由于计算机不能表示无穷精确的数据，在实际运用中会有一个精读取舍，比如求值到 an^2 与 n 的差值小于 0.0000001，或者 an 与 an-1 的差值小于 0.0000001 等等，作为算法（计算）结束的条件。</p>
<h3><a name="_迭代求值的版本"></a>迭代求值的版本</h3>
<table border="0" bgcolor="#e8e8e8" width="100%" cellpadding="10">
<tr>
<td style="padding:0;"><!-- Generator: GNU source-highlight 3.1.6 by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre style="margin:0;"><tt><font color="#000000">(</font><b><font color="maroon">declare</font></b><font color="#000000"> good-enough? improve</font><font color="#000000">)</font>
<font color="#000000">(</font><font color="#000000">def err </font><font color="#000000">0.00000001</font><font color="#000000">)</font>

<font color="#000000">(</font><font color="#000000">defn iter-sqrt [n guess]</font>
<font color="#000000">  </font><font color="#000000">(</font><b><font color="maroon">if</font></b><font color="#000000"> </font><font color="#000000">(</font><font color="#000000">good-enough? guess n</font><font color="#000000">)</font>
<font color="#000000">    guess</font>
<font color="#000000">    </font><font color="#000000">(</font><font color="#000000">iter-sqrt n </font><font color="#000000">(</font><font color="#000000">improve guess n</font><font color="#000000">))))</font>

<i><font color="#808080">;上述是递归函数（实际上迭代，因为是尾递归）是求值的过程。</font></i>

<font color="#000000">(</font><font color="#000000">defn improve [guess n]</font>
<font color="#000000">  </font><font color="#000000">(</font><font color="#000000">/ </font><font color="#000000">(</font><b><font color="maroon">+</font></b><font color="#000000"> guess </font><font color="#000000">(</font><font color="#000000">/ n guess</font><font color="#000000">))</font><font color="#000000"> </font><font color="#000000">2</font><font color="#000000">))</font>

<i><font color="#808080">;improve 就是计算序列中的下一项。</font></i>

<font color="#000000">(</font><font color="#000000">defn good-enough? [guess n]</font>
<font color="#000000">  </font><font color="#000000">(</font><b><font color="maroon">let</font></b><font color="#000000">fn [</font><font color="#000000">(</font><font color="#000000">abs [x] </font><font color="#000000">(</font><b><font color="maroon">if</font></b><font color="#000000"> </font><font color="#000000">(</font><font color="#000000">&#60; x </font><font color="#000000">0</font><font color="#000000">)</font><font color="#000000"> </font><font color="#000000">(</font><b><font color="maroon">-</font></b><font color="#000000"> </font><font color="#000000">0</font><font color="#000000"> x</font><font color="#000000">)</font><font color="#000000"> x</font><font color="#000000">))</font><font color="#000000">]</font>
<font color="#000000">    </font><font color="#000000">(</font><font color="#000000">&#60; </font><font color="#000000">(</font><font color="#000000">abs </font><font color="#000000">(</font><b><font color="maroon">-</font></b><font color="#000000"> </font><font color="#000000">(</font><b><font color="maroon">*</font></b><font color="#000000"> guess guess</font><font color="#000000">)</font><font color="#000000"> n</font><font color="#000000">))</font><font color="#000000"> err</font><font color="#000000">)))</font>

<i><font color="#808080">;good-enough? 使用近似值的平方与被开方数的差值作为衡量标准。</font></i>

<font color="#000000">(</font><font color="#000000">println </font><font color="#000000">(</font><font color="#000000">iter-sqrt </font><font color="#000000">2</font><font color="#000000"> </font><font color="#000000">1.0</font><font color="#000000">))</font>
<i><font color="#808080">;= 1.4142135623746899</font></i>
</tt></pre>
</td>
</tr>
</table>
<p>事实上，上述代码在 Clojure-JVM 中实际执行的时候，并不会针对尾递归左右，因为JVM识别不了，如果需要优化，则需要在 Clojure 代码中存在尾递归的地方使用 recur 代替递归函数， Line7 修改为：</p>
<table border="0" bgcolor="#e8e8e8" width="100%" cellpadding="10">
<tr>
<td style="padding:0;"><!-- Generator: GNU source-highlight 3.1.6 by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre style="margin:0;"><tt><font color="#000000">(</font><font color="#000000">recur n </font><font color="#000000">(</font><font color="#000000">improve guess n</font><font color="#000000">))</font></tt></pre>
</td>
</tr>
</table>
<p>上面迭代求值是很自然的，但存在潜在的问题：终止条件 good-enough? 在 iter-sqrt 内部，如果用户想修改精度，或者修改精度测试方法怎么办？当然可以使用“回调函数”的方法，将 good-enough? 作为 iter-sqrt 的参数传递下来：</p>
<table border="0" bgcolor="#e8e8e8" width="100%" cellpadding="10">
<tr>
<td style="padding:0;"><!-- Generator: GNU source-highlight 3.1.6 by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre style="margin:0;"><tt><font color="#000000">(</font><font color="#000000">defn iter-sqrt [n guess good-enough?] ...</font><font color="#000000">)</font></tt></pre>
</td>
</tr>
</table>
<p>看起来不错，但是 good-enough? 的参数怎么定？新的测试方法如果依赖不同的数据怎么办？（比如需要序列中的相邻两项）。这便是回调函数的问题，看似很灵活，但实际上没有 <strong>根本地</strong> 解耦。如果我们将 good-enough? 完全给用户去做，iter-sqrt 完全不理会 good-enough? 会怎样？这个方案是不是很理想，将问题彻底地分解了 —— 生成（序列）和判断（终止条件）的分离。Clojure 或者函数式编程能提供这样一种模块化能力，这个能力有赖与惰性求值。让我们用 lazy 的思维重新分析上述问题。</p>
<h3><a name="_惰性求值的版本"></a>惰性求值的版本</h3>
<p>函数式编程的一个重要思维是：置底向上（Bottom-Up，参见 Paul Gramhan 的 On Lisp)，就像复合函数是有简单函数一步一步组合起来的，最终构了完整的解答，你不可能一开始就拿出那个最大的函数 —— 这是不可能的。首先我们考虑序列。</p>
<p>序列可以分为两个函数，一个用来计算下一项，另一个用来构建这个序列：</p>
<table border="0" bgcolor="#e8e8e8" width="100%" cellpadding="10">
<tr>
<td style="padding:0;"><!-- Generator: GNU source-highlight 3.1.6 by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre style="margin:0;"><tt><font color="#000000">(</font><font color="#000000">defn next-item [n]</font>
<font color="#000000">  </font><font color="#000000">(</font><font color="#000000">fn [a]</font>
<font color="#000000">    </font><font color="#000000">(</font><font color="#000000">/ </font><font color="#000000">(</font><b><font color="maroon">+</font></b><font color="#000000"> a </font><font color="#000000">(</font><font color="#000000">/ n a</font><font color="#000000">))</font><font color="#000000"> </font><font color="#000000">2</font><font color="#000000">)))</font></tt></pre>
</td>
</tr>
</table>
<p>这是一个高阶函数，(next-item n) 返回计算 n 的平方根序列中下一项的函数，所以2的平方根序列可以表示为：<br /> [ 1.0<br /> ((next-item 2) 1.0)<br /> next-item 2) ((next-item 2) 1.0<br /> next-item 2) ((next-item 2) ((next-item 2) 1.0)<br /> &#8230;]</p>
<table border="0" bgcolor="#e8e8e8" width="100%" cellpadding="10">
<tr>
<td style="padding:0;"><!-- Generator: GNU source-highlight 3.1.6 by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre style="margin:0;"><tt><font color="#000000">(</font><font color="#000000">defn lazy-sqrt [calc-next start]</font>
<font color="#000000">  </font><font color="#000000">(</font><font color="#000000">lazy-seq</font>
<font color="#000000">    </font><font color="#000000">(</font><b><font color="maroon">cons</font></b><font color="#000000"> start</font>
<font color="#000000">      </font><font color="#000000">(</font><font color="#000000">lazy-sqrt calc-next </font><font color="#000000">(</font><font color="#000000">calc-next start</font><font color="#000000">)))))</font></tt></pre>
</td>
</tr>
</table>
<table border="0" bgcolor="#e8e8e8" width="100%" cellpadding="10">
<tr>
<td style="padding:0;"><!-- Generator: GNU source-highlight 3.1.6 by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre style="margin:0;"><tt><font color="#000000">(</font><font color="#000000">defn good-enough? [seq-sqrt err]</font>
<font color="#000000">  </font><font color="#000000">(</font><b><font color="maroon">let</font></b><font color="#000000"> [f </font><font color="#000000">(</font><font color="#000000">first seq-sqrt</font><font color="#000000">)</font><font color="#000000"> n </font><font color="#000000">(</font><font color="#000000">fnext seq-sqrt</font><font color="#000000">)</font><font color="#000000">]</font>
<font color="#000000">    </font><font color="#000000">(</font><b><font color="maroon">let</font></b><font color="#000000">fn [</font><font color="#000000">(</font><font color="#000000">abs [x] </font><font color="#000000">(</font><b><font color="maroon">if</font></b><font color="#000000"> </font><font color="#000000">(</font><font color="#000000">&#60; x </font><font color="#000000">0</font><font color="#000000">)</font><font color="#000000"> </font><font color="#000000">(</font><b><font color="maroon">-</font></b><font color="#000000"> </font><font color="#000000">0</font><font color="#000000"> x</font><font color="#000000">)</font><font color="#000000"> x</font><font color="#000000">))</font><font color="#000000">]</font>
<font color="#000000">      </font><font color="#000000">(</font><b><font color="maroon">if</font></b><font color="#000000"> </font><font color="#000000">(</font><font color="#000000">&#60; </font><font color="#000000">(</font><font color="#000000">abs </font><font color="#000000">(</font><b><font color="maroon">-</font></b><font color="#000000"> f n</font><font color="#000000">))</font><font color="#000000"> err</font><font color="#000000">)</font>
<font color="#000000">        n</font>
<font color="#000000">        </font><font color="#000000">(</font><font color="#000000">good-enough? </font><font color="#000000">(</font><font color="#000000">rest seq-sqrt</font><font color="#000000">)</font><font color="#000000"> err</font><font color="#000000">)))))</font></tt></pre>
</td>
</tr>
</table>
<table border="0" bgcolor="#e8e8e8" width="100%" cellpadding="10">
<tr>
<td style="padding:0;"><!-- Generator: GNU source-highlight 3.1.6 by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
<pre style="margin:0;"><tt><font color="#000000">(</font><font color="#000000">println </font><font color="#000000">(</font><font color="#000000">good-enough? </font><font color="#000000">(</font><font color="#000000">lazy-sqrt </font><font color="#000000">(</font><font color="#000000">next-item </font><font color="#000000">2</font><font color="#000000">)</font><font color="#000000"> </font><font color="#000000">1.0</font><font color="#000000">)</font><font color="#000000"> </font><font color="#000000">0.00001</font><font color="#000000">))</font>
<i><font color="#808080">;= 1.4142135623746899</font></i></tt></pre>
</td>
</tr>
</table>
<p>上面的计算可以翻译成：比较之前的迭代版本是不是“说得”更好？</p>
<h3><a name="_参考"></a>参考</h3>
<ol type="1">
<li> Abelson, H. and Sussman, G. J. &#8211; 计算机程序的结构和解释（SICP） </li>
<li> John Hughes &#8211; Why Funtional Programming Matters </li>
</ol></div>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Risk Measurement On-demand: Complexity, Volatility, Regulatory Uncertainty]]></title>
<link>http://financegraphics.wordpress.com/2012/07/20/risk-measurement-on-demand-complexity-volatility-regulatory-uncertainty/</link>
<pubDate>Fri, 20 Jul 2012 09:31:22 +0000</pubDate>
<dc:creator>admin</dc:creator>
<guid>http://financegraphics.wordpress.com/2012/07/20/risk-measurement-on-demand-complexity-volatility-regulatory-uncertainty/</guid>
<description><![CDATA[Infographic from FINCAD on what factors are affecting the financial industry and why firms need  ris]]></description>
<content:encoded><![CDATA[<p>Infographic from FINCAD on what factors are affecting the financial industry and why firms need  risk measurement on-demand to cope with the changing markets and to measure risk at all levels. Factors include billions of losses from fraud, tighter regulations on financial derivatives, and higher market volatility.</p>
<p><a href="http://financegraphics.files.wordpress.com/2012/07/fincad-tabb-risk-measurement-horizontal.jpg"><img class="aligncenter size-full wp-image-179" title="FINCAD-TABB-Risk-measurement-horizontal" src="http://financegraphics.files.wordpress.com/2012/07/fincad-tabb-risk-measurement-horizontal.jpg?w=470&#038;h=235" alt="" width="470" height="235" /></a></p>
<p>Via FINCAD on Pinterest <a href="http://pinterest.com/pin/11470174021588278/">http://pinterest.com/pin/11470174021588278/</a>. Information based on report with the same name <a href="http://www.fincad.com/derivatives-resources/white-papers/risk-measurement-on-demand.aspx">http://www.fincad.com/derivatives-resources/white-papers/risk-measurement-on-demand.aspx</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[TransLucid 0.2 released]]></title>
<link>http://thenewcpp.wordpress.com/2012/06/22/translucid-0-2-released-2/</link>
<pubDate>Thu, 21 Jun 2012 21:08:02 +0000</pubDate>
<dc:creator>Jarryd Beck</dc:creator>
<guid>http://thenewcpp.wordpress.com/2012/06/22/translucid-0-2-released-2/</guid>
<description><![CDATA[TransLucid version 0.2 has been released. With this release comes the ability to replace and delete]]></description>
<content:encoded><![CDATA[TransLucid version 0.2 has been released. With this release comes the ability to replace and delete]]></content:encoded>
</item>
<item>
<title><![CDATA[#610 - Lazy Evaluation in Property Get Accessors]]></title>
<link>http://csharp.2000things.com/2012/06/21/610-lazy-evaluation-in-property-get-accessors/</link>
<pubDate>Thu, 21 Jun 2012 11:00:19 +0000</pubDate>
<dc:creator>Sean</dc:creator>
<guid>http://csharp.2000things.com/2012/06/21/610-lazy-evaluation-in-property-get-accessors/</guid>
<description><![CDATA[One of the benefits in using a property in a class, rather than a public field, is that you can dela]]></description>
<content:encoded><![CDATA[<p>One of the benefits in using a property in a class, rather than a public field, is that you can delay calculation of the property&#8217;s value until client code actually tries to read the value.</p>
<p>In the code below, we define a <strong>FullDogDescription</strong> property that is read-only.  The private backing variable is initialized to an empty string and we only calculate its value in the <strong>get</strong> accessor when someone tries to read the property&#8217;s value.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
&#60;pre&#62;        private string fullDogDescription = &#34;&#34;;
        public string FullDogDescription
        {
            get
            {
                // Generate full description the first time that
                // someone reads this property.
                if (fullDogDescription == &#34;&#34;)
                    fullDogDescription = GenerateDogDescription();

                return fullDogDescription;
            }
        }
</pre>
<p>The benefit of doing this is that if the call to <strong>GenerateDogDescription</strong> takes some time, we don&#8217;t spend the time calculating a value until some piece of code actually needs a value.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Contribution on Lazy Evaluation at Wikipedia]]></title>
<link>http://technobeans.wordpress.com/2012/06/12/contribution-on-lazy-evaluation-at-wikipedia/</link>
<pubDate>Tue, 12 Jun 2012 12:08:04 +0000</pubDate>
<dc:creator>Chetan Giridhar</dc:creator>
<guid>http://technobeans.wordpress.com/2012/06/12/contribution-on-lazy-evaluation-at-wikipedia/</guid>
<description><![CDATA[Recently made a contribution to Wikipedia article on Lazy Evaluation in Python section. You can have]]></description>
<content:encoded><![CDATA[Recently made a contribution to Wikipedia article on Lazy Evaluation in Python section. You can have]]></content:encoded>
</item>
<item>
<title><![CDATA[Cafeteria Points]]></title>
<link>http://mrbryanbanks.wordpress.com/2012/04/04/cafeteria-points/</link>
<pubDate>Wed, 04 Apr 2012 23:50:42 +0000</pubDate>
<dc:creator>Bryan</dc:creator>
<guid>http://mrbryanbanks.wordpress.com/2012/04/04/cafeteria-points/</guid>
<description><![CDATA[Why do we pay $100 a person to see this? Image via Wikipedia I’ve worked at my current job for a lit]]></description>
<content:encoded><![CDATA[Why do we pay $100 a person to see this? Image via Wikipedia I’ve worked at my current job for a lit]]></content:encoded>
</item>
<item>
<title><![CDATA[Functional Programming and Haskell]]></title>
<link>http://sudocoding.wordpress.com/2012/02/14/functional-programming-and-haskell/</link>
<pubDate>Tue, 14 Feb 2012 16:36:50 +0000</pubDate>
<dc:creator>Daniel Tahara</dc:creator>
<guid>http://sudocoding.wordpress.com/2012/02/14/functional-programming-and-haskell/</guid>
<description><![CDATA[Hey everyone &#8212; sorry it&#8217;s been a while since my last post.  School got off to a crazy st]]></description>
<content:encoded><![CDATA[<p>Hey everyone &#8212; sorry it&#8217;s been a while since my last post.  School got off to a crazy start, and I&#8217;ve been really busy planning a <a title="Yale Hackathon" href="http://hackerleague.org/hackathons/yale-hackathon" target="_blank">hackathon</a>, writing <a title="HackYale iOS Course Materials" href="https://github.com/brandonjackson/hackYaleiOS" target="_blank">material</a> for my <a title="HackYale iOS" href="http://hackyale.com/courses/ios" target="_blank">iOS course</a>, and just generally being involved with life on campus.  Oh right, and I am taking a few CS courses, too.</p>
<p>This post in particular is dedicated to a hidden gem that I found, and one that has given me a new way to look at programming and problem solving:</p>
<p>In addition to taking my two core CS courses, Data Structures and Algorithms, I enrolled in a a linguistics course that explores how we can represent and manipulate meaning in a computer.  In order to do that, we are learning Haskell. It is an incredible language. Here&#8217;s where I&#8217;ve been learning, and here&#8217;s the scoop:</p>
<p>It&#8217;s functional. What does that mean? I had learned Scheme for my introduction to CS course, but I did not understand the essence of functional programing. It&#8217;s based on lambda calculus, which is a system for manipulating functions.  Essentially, the lambda &#8220;term&#8221; are defined as follows (you can read more <a title="Lambda Calculus" href="http://www.utdallas.edu/~gupta/courses/apl/lambda.pdf" target="_blank">here</a> if you&#8217;re interested):</p>
<ol>
<li>Any variable or atomic statement, x</li>
<li>Abstraction, λx . M &#8211; i.e. turn M into a function, with x as the variable</li>
<li>Application, (M N) &#8211; i.e. replace every appearance of x in M (see 2) with N</li>
</ol>
<p>It may seem a bit confusing, but it is quite similar to how we think about math.  You have functions, denoted f(x) or the like, and you can apply that function to x.  Alternatively, given some expression (without an equal sign), you can turn it into a function by setting it equal to g(x) or the like.  The single most powerful feature of lambda calculus is the ability to pass a function as an argument to another function.  Just like we can apply a function to a variable or a constant (1), we can also do something like f(g(x)) and get a totally new function which we can then apply to some other expression.  What&#8217;s more, and here is a place lambda calculus gets cool, is that if a function takes multiple variables, if we give it a value for one of the variables, it becomes a totally new, and perfectly legal function.  This has tremendous implications for how we can manipulate data, and gives you the opportunity to write highly flexible code.</p>
<p>But enough of my raving.  If you don&#8217;t believe me, read <a href="http://www.haskell.org/haskellwiki/Why_Haskell_matters" target="_blank">this</a>, <a href="http://www.haskell.org/haskellwiki/Introduction" target="_blank">this</a>, or <a href="http://www.cse.chalmers.se/~rjmh/Papers/whyfp.pdf" target="_blank">this</a>.  And get started learning Haskell!  Here are my favorite things about the language:</p>
<ul>
<li>Strong typing &#8211; the compiler will yell at you if your types don&#8217;t match exactly.  Seriously.  And ghc (glasgow haskell compiler) will give you very precise, useful error messages.  This prevents a lot of runtime errors, and usually means that you will have a working program once it has successfully compiled.</li>
<li>First class functions &#8211; since Haskell is functional, there is no concept of &#8220;parameters&#8221; per se, only terms to which you are applying a function.  Because of this, functions are applied to terms immediately following them, and function application takes the highest precedence.  Say goodbye to parentheses!</li>
<li>First class math &#8211; so many built in functions for math.  One line fibonacci sequence. &#8216;Nuff said.  Maybe not &#8211; the use of guards instead of if-else statements makes code look like real, pencil-and-paper math</li>
<li>Infinite lists &#8211; didn&#8217;t think that was possible?  Thank <a href="http://en.wikibooks.org/wiki/Haskell/Laziness" target="_blank">laziness</a>.</li>
</ul>
<p>Sold?  If you&#8217;re interested in learning the language, I would start with <a href="http://learnyouahaskell.com/" target="_blank">Learn You a Haskell</a>, which gives a great rundown of all the important library functions, as well as gives you a good sense of how to use the functional constructs of Haskell.  More advanced programmers may want to look <a href="http://www.haskell.org/haskellwiki/Tutorials" target="_blank">here</a>.</p>
<h6 class="zemanta-related-title" style="font-size:1em;">Related articles</h6>
<ul class="zemanta-article-ul">
<li class="zemanta-article-ul-li"><a href="http://stackoverflow.com/questions/8153350/haskell-lazyness">Haskell Lazyness</a> (stackoverflow.com)</li>
</ul>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Vacation turns into runaway train - Stresser of the Day]]></title>
<link>http://thedailystresser.wordpress.com/2011/12/28/vacation-turns-into-runaway-train-stresser-of-the-day/</link>
<pubDate>Thu, 29 Dec 2011 00:02:24 +0000</pubDate>
<dc:creator>mgregory</dc:creator>
<guid>http://thedailystresser.wordpress.com/2011/12/28/vacation-turns-into-runaway-train-stresser-of-the-day/</guid>
<description><![CDATA[Vacation time, ah the joys of going to bed late, rising after the sun has warmed the ground and brig]]></description>
<content:encoded><![CDATA[Vacation time, ah the joys of going to bed late, rising after the sun has warmed the ground and brig]]></content:encoded>
</item>
<item>
<title><![CDATA[IEnumerable&lt;char&gt; Random Password Generator]]></title>
<link>http://brianreiter.org/2011/01/15/ienumerablechar-random-password-generator/</link>
<pubDate>Sat, 15 Jan 2011 14:50:55 +0000</pubDate>
<dc:creator>Brian Reiter</dc:creator>
<guid>http://brianreiter.org/2011/01/15/ienumerablechar-random-password-generator/</guid>
<description><![CDATA[Last time I showed that IEnumerable uses lazy evaluation with a Fibonacci Sequence generator as an e]]></description>
<content:encoded><![CDATA[<p><a href="https://thoughtfulcode.wordpress.com/2011/01/14/ienumerable-is-lazy-and-thats-cool/" target="_blank">Last time I showed that IEnumerable uses lazy evaluation</a> with a Fibonacci Sequence generator as an example. Perhaps a more practical example of an infinite series is a random character sequence from which you could generate passwords. This is using IEnumerable a lot like the /dev/random file in Unix.</p>
<p>This example is a password generator program based on a RandomCharSequence type which implements IEnumerable&#60;char&#62;. RandomCharSequence is again not much more than a factory for RandomCharEnumerator. The interesting thing here is that it passes the set of characters to be used in the random generation to RandomCharEnumerator. The character sets are upper, lower, digit and special and are themselves statically defined but are composable&#160; using a CharTypes enumeration.</p>
<p>Like FibonacciSequence, RandomCharSequence is an infinite set. You have to limit how much of it you grab at a particular time using the Take(int) extension method from System.Linq.</p>
<h2>RandomCharSequence as Password Generator</h2>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:377daf87-dc31-4de6-97d1-c3bde68697c5" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; pad-line-numbers: true; title: ; notranslate" title="">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Security.Cryptography;
using System.Reflection;
using System.Collections.ObjectModel;

namespace NewPassword
{
    class Program
    {
        static void Main( string[] args )
        {
            int length = -1;
            int count  = -1;
            if( args.Length &#62; 0 )
            { int.TryParse( args[0], out length ); }
            else
            { length = 8; }
            if( args.Length &#62; 1 )
            { int.TryParse( args[1], out count ); }
            else
            { count = 5; }
            
            var pwdseq = new RandomCharSequence();
            for( int i = 0; i &#60; count; i++ )
            {
                Console.WriteLine( pwdseq.Take( length ).ToArray() );
            }
        }
    }

    [Flags]
    public enum CharTypes
    {
        Lower   = 0x01,
        Upper   = 0x02,
        Digit   = 0x04,
        Special = 0x08,
        All     = Upper &#124; Lower &#124; Digit &#124; Special
    }
    public class RandomCharSequence : IEnumerable&#60;char&#62;
    {
        static readonly IEnumerable&#60;char&#62; s_lower   = new[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'q', 'y', 'z' };
        static readonly IEnumerable&#60;char&#62; s_upper   = new[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'Q', 'Y', 'Z' };
        static readonly IEnumerable&#60;char&#62; s_digit   = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        static readonly IEnumerable&#60;char&#62; s_special = new[] { '!', '&#34;', '#', '$', '%', '&#38;', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '&#60;', '=', '&#62;', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '&#124;', '}', '~' };

        //these static properties must exactly match the flags defined in the CharTypes enum
        private static IEnumerable&#60;Char&#62; Lower   { get{ return s_lower; } }
        private static IEnumerable&#60;Char&#62; Upper   { get{ return s_upper; } }
        private static IEnumerable&#60;Char&#62; Digit   { get{ return s_digit; } }
        private static IEnumerable&#60;Char&#62; Special { get{ return s_special; } }

        public RandomCharSequence() : this( CharTypes.All ){}
        public RandomCharSequence( CharTypes charTypes )
        {
            CharTypes = charTypes;
        }

        public CharTypes CharTypes {get; set;}

        public IEnumerator&#60;char&#62; GetEnumerator()
        {
            List&#60;char&#62; pool = new List&#60;char&#62;();
            foreach( var type in (CharTypes[])Enum.GetValues(typeof(CharTypes) ) )
            {
                //CharTypes.All is not a single bit flag. We don't want that one.
                if( type != CharTypes.All &#38;&#38; (CharTypes &#38; type) == type )
                {
                    //use reflection to add the static char list properties which
                    //match the flag bits.
                    pool.AddRange( 
                        (IEnumerable&#60;char&#62;)typeof(RandomCharSequence).GetProperty( 
                            type.ToString(), 
                            BindingFlags.Static &#124; BindingFlags.NonPublic 
                            ).GetValue( this, null )
                        );
                }
            }
            return new RandomCharEnumerator( pool );
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    public class RandomCharEnumerator : IEnumerator&#60;char&#62;
    {
        public RandomCharEnumerator( IList&#60;char&#62; pool )
        {
            Disposing = false;
            Pool      = new ReadOnlyCollection&#60;char&#62;( pool );
            Random    = RandomNumberGenerator.Create();
        }

        RandomNumberGenerator Random { get; set; } 
        public IList&#60;char&#62; Pool { get; private set; }
        int Index { get; set; }

        public char  Current
        {
            get { return Pool[Index]; }
        }
        object IEnumerator.Current { get { return Current; } }


        private bool Disposing{ get; set; }
        public void  Dispose()
        {
            //RandomNubmerGenerator only implements IDisposable as of .NET Framework 4.0
            IDisposable randDisposable = Random as IDisposable;
            if( randDisposable != null &#38;&#38; !Disposing )
            {
                randDisposable.Dispose();
                Disposing = true;
            }
        }

        public bool  MoveNext()
        {
            Index = Random.GetInt( 0, Pool.Count );
            //infinite sequence of random chars. There's always a next one.
            return true;
        }

        public void  Reset(){ /* nothing */ }
    }

    public static class RandomNumberGeneratorExtension
    {
        public static int GetInt( this RandomNumberGenerator random, int min, int max )
        {
            if( min &#62;= max )
                throw new InvalidOperationException( &#34;The min value must be less than the max value.&#34; );
            byte[] buff = new byte[8];
            random.GetBytes(buff);
            long r = Math.Abs( BitConverter.ToInt64( buff, 0 ) );
            return (int)((long)min + (r % ((long)max - (long)min)));
        }
    }
}

</pre>
</div>
<p>Compile and run the program to pull some password strings out of the infinite random character sequence.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:4aaec160-b1ab-48c1-9a22-9e38cb3516d9" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: powershell; pad-line-numbers: true; title: ; notranslate" title="">
PS&#62; csc -nologo -out:newpassword.exe ./Program.cs; ./newpassword 10 15
^mVhNjHdds
o4Eq=q;`es
%1R\rL3r3{
+PFRrl4e)u
TvAB+tjNu-
?8zCq~{?KB
@WY)+sF;^I
B+)'?sRee-
G'\e)QkjYp
L8(`@o};$$
)j`$7?RG)4
QcC{4;fZcb
_S89_tm]76
}kAiirj^!=
,qq&#124;%-(s)@
</pre>
</div>
<p><em>Update: RandomNumberGenerator does not implement IDisposable until .Net Framework 4.0 so I needed to dynamically invoke the interface if present rather than statically compiling with Random.Dispose() in there.</em></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[IEnumerable is Lazy&hellip; And That&rsquo;s Cool]]></title>
<link>http://brianreiter.org/2011/01/14/ienumerable-is-lazy-and-thats-cool/</link>
<pubDate>Fri, 14 Jan 2011 19:18:10 +0000</pubDate>
<dc:creator>Brian Reiter</dc:creator>
<guid>http://brianreiter.org/2011/01/14/ienumerable-is-lazy-and-thats-cool/</guid>
<description><![CDATA[We tend to think of IEnumerable&lt;T&gt; as this thing in C# collections which allows foreach to ite]]></description>
<content:encoded><![CDATA[<p>We tend to think of <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" target="_blank"><span style="font-family:'Courier New';">IEnumerable&#60;T&#62;</span></a> as this thing in C# collections which allows <a href="http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx" target="_blank"><span style="font-family:'Courier New';">foreach</span></a><span style="font-family:Consolas;"> </span>to iterate a collection without having to deal with a counter. There’s another semantic feature of IEnumerable that is different from an <a href="http://msdn.microsoft.com/en-us/library/system.array.aspx" target="_blank"><span style="font-family:'Courier New';">Array</span></a> or <a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx" target="_blank"><span style="font-family:'Courier New';">List&#60;T&#62;</span></a> or any other concrete collection. IEnumerable is <a href="http://en.wikipedia.org/wiki/Lazy_evaluation" target="_blank">lazy</a> while an array or list is implicitly <a href="http://en.wikipedia.org/wiki/Eager_evaluation" target="_blank">eager</a>.</p>
<p>Consider an array. First, you have to define its size which is fixed. Then you have to loop over the array and populate it with values. Then you can use it in some other loop later. Array is conducive to eager evaluation because you have to define its size in advance and you have to fill it up before you can use it. Lists are similar conceptually and are actually implemented with arrays internally. The main advantage of a list is that it is dynamically expandable.</p>
<p>IEnumerable is a very different thing. At its core IEnumerable is a contract to provide a factory for an <a href="http://msdn.microsoft.com/en-us/library/78dfe2yb.aspx" target="_blank"><span style="font-family:'Courier New';">IEnumerator&#60;T&#62;</span></a> object. IEnumerator then just provides a mechanism to get the current element of the enumeration, move to the next element and reset. IEnumerator only has to know how to get the next element or start over. It doesn’t actually need a collection to exist. <a href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.movenext.aspx" target="_blank"><span style="font-family:'Courier New';">MoveNext()</span></a> only has to get the next value. There’s no requirement that all values are known at any give time and there’s no requirement that the values are finite. This is the essence of lazy evaluation. Only enough work needs to be done to get the next answer. Nothing more.</p>
<h2>Fibonacci: An infinite <span style="font-family:'Courier New';">IEnumberable&#60;T&#62;</span></h2>
<p>To illustrate that IEnumerable is a lazy evaluation pattern, I implemented the <a href="http://en.wikipedia.org/wiki/Fibonacci_number" target="_blank">Fibonacci Sequence</a> as an enumerable type in C#. I can pass a FibonacciSequence object to things that understand IEnumerable and it works. If IEnumerable were an eager implementation my code would spin in an infinite loop but it doesn’t because MoveNext() only calculates the next number in the series if it is asked.</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:4db57630-27ef-45f0-bc8b-48f426e72aa8" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;">
<pre class="brush: csharp; title: ; notranslate" title="">
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

namespace LazyFibonacci
{
    class Program
    {
        static void Main( string[] args )
        {
            int i = -1;
            if( args.Length &#62; 0 )
            { int.TryParse( args[0], out i ); }
            else
            { i = 100; }

            var fibonacci = new FibonacciSequence();
            /***
             * fibonacci is infinite.
             * Don't try operations that require the entire set to be enumerated:
             *  - fibinacci.ToList() --&#62; NO!
             *  - fibonacci.Reverse() --&#62; NO!
             *
             * Using .Skip(int) and .Take(int) is a good way to get slices of fibonacci, though.
             ***/

            foreach( var item in fibonacci.Take( i ) )
            {
                Console.WriteLine( item );
            }
        }
    }

    //FibonnacciSequence has no state.
    //It's just a factory for FibonacciEnumerator.
    public class FibonacciSequence : IEnumerable&#60;BigInteger&#62;
    {
        public IEnumerator&#60;BigInteger&#62; GetEnumerator()
        {
            return new FibonacciEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    public class FibonacciEnumerator : IEnumerator&#60;BigInteger&#62;
    {
        public FibonacciEnumerator()
        {
            Reset();
        }

        BigInteger Last { get; set; }
        public BigInteger Current { get; private set; }
        object IEnumerator.Current { get { return Current; } }

        public void Dispose() { /*do nothing*/}

        public void Reset()
        {
            Current = -1;
        }

        public bool MoveNext()
        {
            if( Current == -1 )
            {
                //State after first call to MoveNext() before the first element is read
                //Fibonacci is defined to start with 0.
                Current = 0;
            }
            else if( Current == 0 )
            {
                //2nd element in the Fibonacci series is defined to be 1.
                Current = 1;
            }
            else
            {
                //Fibonacci infinite series algorithm.
                BigInteger next = Current + Last;
                Last = Current;
                Current = next;
            }
            //infinite series. there is always another.
            return true;
        }
    }
}

</pre>
</div>
<p>The moment of truth. If IEnumerable is lazy this will work.</p>
<p>&#160;</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:26ca73b0-d121-4f48-b46a-a835fe9c222c" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;">
<pre class="brush: powershell; light: false; pad-line-numbers: true; title: ; notranslate" title="">
PS&#62; csc -nologo -r:System.Numerics.dll -out:fibonacci.exe ./program.cs
PS&#62; $fib = (./fibonacci.exe 25); [string]::join(', ', $fib)
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368

</pre>
</div>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Haskell Tutorial IV :  If This is A Case of Functional Programming, Then I am Switching to Lazy Evaluation]]></title>
<link>http://otherlibrarian.wordpress.com/2010/10/21/haskell-tutorial-iv-if-this-is-case-of-functional-programming-then-i-am-switching-to-lazy-evaluation/</link>
<pubDate>Thu, 21 Oct 2010 19:40:36 +0000</pubDate>
<dc:creator>Ryan Deschamps</dc:creator>
<guid>http://otherlibrarian.wordpress.com/2010/10/21/haskell-tutorial-iv-if-this-is-case-of-functional-programming-then-i-am-switching-to-lazy-evaluation/</guid>
<description><![CDATA[&lt; Part III: How Haskell Monads are Like a Muppet       Part: V   (coming soon) &gt; Finally, with]]></description>
<content:encoded><![CDATA[<p style="text-align:center;">&#60; <a title="How Haskell Monads are Like a Muppet" href="http://otherlibrarian.wordpress.com/2010/10/19/part-iii-how-haskell-monads-are-like-a-muppet/">Part III: How Haskell Monads are Like a Muppe</a>t       Part: V   (coming soon) &#62;</p>
<p>Finally, with the forth part of the tutorial, I get to describe something that will make my PHP-coding reader want to use Haskell:  lazy evaluation.</p>
<p>But first, let&#8217;s go back to two different ways I&#8217;ve approached the problem of evaluating a keyboard input from a user in our rogue-like RPG game.    In tutorial #2, I created a function called move that used guards to discern what action to take based on a given input.    Here is move:</p>
<pre>move :: Char -&#62; String
move a
    &#124;  a == 'w'       = "UP!"
    &#124;  a == 's'       = "DOWN!"
    &#124;  a == 'a'       = "LEFT!"
    &#124;  a == 'd'       = "RIGHT!"
    &#124;  otherwise      = "HANG AROUND AND DO NOTHING!"</pre>
<p>In tutorial #3 I switched to a series of if / else if / else statements.</p>
<pre>forever (do
    char &#60;- getChar
    if char == 'q' then putStrLn "Thanks for Playing!"
         else if char == 'w' then up y &#62;&#62; output x &#62;&#62; output y
         else if char == 's' then down y &#62;&#62; output x &#62;&#62; output y
         else if char == 'a' then down x &#62;&#62; output x &#62;&#62; output y
         else if char == 'd' then up x &#62;&#62; output x &#62;&#62; output y
         else putStrLn "you did not type a correct entry")</pre>
<p>This version had the additional side effect of requiring a manual escape of the compiler program in order to quit (something that is easily fixable, but still).    Now I have a new function &#8216;dashboard&#8217; that uses lazy evaluation to compute values based on a given input.   Without beating around the bush, here it is:</p>
<pre>dashboard :: Char -&#62; MVar Int -&#62; MVar Int -&#62; IO ()
dashboard 'q' _ _ = exit "Thanks for Playing!"    // stop the program
dashboard 'w' x y = up y &#62;&#62; putStr " Coordinate: ( x = " &#62;&#62; output x &#62;&#62; putStr " , y = " &#62;&#62; output y &#62;&#62; putStr ")."
dashboard 's' x y = down y &#62;&#62; putStr " Coordinate: ( x = " &#62;&#62; output x &#62;&#62; putStr ", y = " &#62;&#62; output y &#62;&#62; putStr ")."
dashboard 'a' x y = down x &#62;&#62; putStr " Coordinate: ( x = " &#62;&#62; output x &#62;&#62; putStr ", y = " &#62;&#62; output y &#62;&#62; putStr ")."
dashboard 'd' x y = up x &#62;&#62; putStr " Coordinate:  ( x = " &#62;&#62; output x &#62;&#62; putStr ", y = " &#62;&#62; output y &#62;&#62; putStr ")."
dashboard w x y = putStr " Coordinate: ( x = " &#62;&#62; output x &#62;&#62; putStr ", y = " &#62;&#62; output y &#62;&#62; putStr ")."   // keep the Coordinate values the same</pre>
<p>So, let&#8217;s think about our problem for a second.    So far, we have been focussed on getting our character to move around a map.    But what if we want to do something completely different, like say show an inventory list if the user hits &#8216;i&#8217;?    Or maybe cast a spell?     We could have a bunch of if &#8211; then statements or a whole bunch of guards, but it all could end up being a mess and impossible to read.</p>
<p>Fortunately, Haskell let&#8217;s you specify particular actions based on the constructors (entry values) for your function.    In the case above, dashboard accepts 3 values &#8212; one CHAR and two MVar Ints (ie. a mutable variable that has to be an integer &#8212; <a href="http://otherlibrarian.wordpress.com/2010/10/19/part-iii-how-haskell-monads-are-like-a-muppet/">see the previous tutorial</a>).   If the dashboard receives a &#8216;q&#8217; for a value, it will say &#8216;thanks for playing&#8217; and quit the program (the two &#8216;_&#8217;s mean it doesn&#8217;t matter what the values are that follow it).   The next entries do what we&#8217;ve come to expect -&#62; change the value of the MVar based on the movement and then output the current coordinate&#8217;s status.    The last statement is a catch-all, asking Haskell to output the current spot.</p>
<p>Why might this way of doing things be better than using (say) guards?    Well, the first reason is that it gets to the point.    if the user hits &#8216;q&#8217;, Haskell will not attempt to evaluate any of the other function calls.   Admittedly, this function isn&#8217;t really helped performance-wise by lazy evaluation -&#62; but what if moving in a certain direction (in the spot where a monster was) involved a long series of recursive computations.    We would not want Haskell to be using up its resources trying to figure out what it&#8217;s supposed to do when all the user wants to do is quit.</p>
<p>However, there&#8217;s still alot that could be added here.   What if we want to do something when the user hits &#8216;s&#8217; and y is equal to zero.    Then we could do something like this:</p>
<pre>dashboard 's' 0 y putStrLn "You are blocked and can go no further."  &#62;&#62; putStr " Coordinate:  ( x = " &#62;&#62; output x &#62;&#62; putStr ", y = " &#62;&#62; output y &#62;&#62; putStr ")."</pre>
<p>Again, this can have really great performance benefits for your program.    If dashboard gets an &#8216;s&#8217; and a &#8217;0&#8242;, it will look no further and do the easy job of outputting the coordinate as is, rather than attempting to go through all kinds of irrelevant processes.   UPDATE:  <em>Well, actually, this is all wrong.    Because &#8217;0&#8242; is not an MVAR.    Mind you, there is a way to get the function to accept two Ints instead and convert the MVAR to an Int for our purposes.    That&#8217;ll be another tutorial though.</em></p>
<p>The last benefit is that it gives a nice human-readable understanding of what happens when the function receives what, without a whole range of complex nested elements.</p>
<p>The downside, of course, is that because Haskell is type-safe, you must give this function a CHAR (not a Maybe Char, or a String) and two MVAR Ints (not an MVAR String or ordinary Int) or you will get a type error.       Things could also get more confusing if you decide that you want to return an IO (String) or other value instead of just outputting something to the screen.    But handling that problem might be for another tutorial.</p>
<p>I should, again, remind you that my up-to-date work on the <a title="Raghiosse Source Code" href="https://patch-tag.com/r/greebie/rasghiosse/home">rogue-like game called rasghiosse is available in a patch-tag repository</a>.   Please feel free to add to it as you wish.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Lazy Evaluation]]></title>
<link>http://mauricioszabo.wordpress.com/2009/11/29/lazy-evaluation/</link>
<pubDate>Mon, 30 Nov 2009 01:34:04 +0000</pubDate>
<dc:creator>Maurício Szabo</dc:creator>
<guid>http://mauricioszabo.wordpress.com/2009/11/29/lazy-evaluation/</guid>
<description><![CDATA[Existe um conceito, muito utilizado por programadores de linguagens funcionais e pouco utilizado em]]></description>
<content:encoded><![CDATA[<p>Existe um conceito, muito utilizado por programadores de linguagens funcionais e pouco utilizado em outras linguagens, chamado <a href="http://en.wikipedia.org/wiki/Lazy_evaluation">Lazy Evaluation</a>. Para não extender muito a definição, basta dizer que no caso do Lazy Evaluation, um resultado só é computado quando ele é necessário ao programa. Exemplos explicam melhor o conceito, então segue um:</p>
<pre><pre class="brush: ruby; title: ; notranslate" title="">
100.times do &#124;iterador&#124; #Equivalente ao &#34;for&#34; de outras linguagens
  n = fatorial(iterador)  #Calcula o fatorial
  if(iterador.even?)       #Se for um número PAR
    print &#34;Resultado da operação: #{n}&#34; #Imprime o resultado do fatorial
  end
end
</pre>
<p>Lembrando que Ruby não trabalha com Lazy Evaluation, portanto o código acima não seria adequado. Mas, digamos que a linguagem acima suporte Lazy Evaluation: o resultado de <b>n</b> só seria calculado se o iterador for par. Ou seja, embora estejamos sempre definindo que n = fatorial(iterador), o programa não <strong>calcula</strong> o resultado do fatorial até que precisemos dele - neste caso, até que ele seja impresso na tela. Ou seja, em linguagens como Haskell, que suportam Lazy Evaluation por padrão, o código acima seria perfeitamente válido e não seria ineficiente. Normalmente, quando você usa Lazy Evaluation o código que só rodará depois é chamado de "promisse", pois ele é uma promessa que o valor será calculado.</p>
<p>Mas porque isso é tão interessante?</p>
<p><!--more--></p>
<p>Justamente, porque atrasar o cálculo de algo pode te dar maior fluidez em alguns outros momentos. Já citei anteriormente sobre o <a href="http://mauricioszabo.wordpress.com/2009/10/06/datamapper-versus-activerecord">DataMapper</a>, que na hora de fazer uma busca retorna apenas uma "promessa" que que irá buscar, e se você precisar apenas do primeiro elemento do Array ele buscará apenas o primeiro elemento. Também, no <a href="http://mauricioszabo.wordpress.com/2009/11/24/paradigmas-do-mongodb/">MongoParadigm</a> (meu projeto de um mapeador para MongoDB) estou tentando deixá-lo Lazy, pois gostaria mesmo de aproveitar alguns conceitos do DataMapper para o Mongo. Mas esses dias, tive um problema diferente:</p>
<p>Estava trabalhando num passatempo, uma interface para listar os documentos do MongoDB. Estava usando Qt4, Ruby, e eu tinha uma coleção de documentos com 600 mil documentos (imagine 600 mil registros numa tabela, como comparação). O problema é que eu exibiria apenas um elemento por vez, e teriam dois botões (próximo e anterior), e não faria sentido nenhum ficar buscando os documentos sempre que eu apertasse em próximo ou anterior (afinal, é um projeto offline e eu queria fluidez total). Também, seria impossível buscar os 600 mil de uma vez e popular um Array com todos eles, afinal isso demoraria muito tempo e acabaria com a idéia de fluidez. Então, pensei em usar Threads, mas... <a href="http://www.zeroc.com/forums/comments/2742-ice-ruby-qt-example.html">Qt4 não suporta Threads</a> do Ruby.</p>
<p>O que fazer? Aprender GTK para Ruby, e ter que lidar com uma mudança de quase todo o código? Mudar de linguagem? Achar um jeito de rodar Threads nativas em Ruby, e sabe-se lá como lidar com essa nova complexidade? usar um timer e ficar buscando de tempos em tempos novos objetos?</p>
<p>A solução foi razoavelmente simples: criar um "buscador", que mantém um registro de qual busca foi feita e do número de registros que a coleção possui. Criar um "Hash" para armazenar todos os registros, e a partir daí, sempre que um registro for requisitado, e se ele não existir no Hash, ele é buscado (junto com mais alguns registros à frente dele) e armazenado no hash. Desta forma, fica bem mais fluído e até mesmo é uma solução bem mais elegante do que o uso de Threads.</p>
<p>Mas... até quando usar Lazy Evaluation?</p>
<p>Note que não é uma "bala de prata", que nem todos os problemas são solucionado usando Lazy Evaluation. Algumas vezes, usar Lazy Evaluation mais atrapalha do que ajuda - especialmente nas linguagens como Ruby que não a suportam nativamente. Isso porque, algumas vezes, você soluciona um problema mas deixa seu programa mais difícil de entender, ou os erros não ficam muito visíveis.</p>
<p>Mais à frente, eu tento postar novidades sobre o assunto. Por hora, a interface gráfica está no meu GitHub, basta cloná-la e testá-la (note que você precisará do driver Mongo para Ruby e do Qt4).</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[C/AL++]]></title>
<link>http://xosfaere.wordpress.com/2009/06/30/navision-lazy-evaluation/</link>
<pubDate>Tue, 30 Jun 2009 05:43:32 +0000</pubDate>
<dc:creator>xosfaere</dc:creator>
<guid>http://xosfaere.wordpress.com/2009/06/30/navision-lazy-evaluation/</guid>
<description><![CDATA[Navision C/AL can be quite monotonous to develop in &#8211; which is also one of its strengths]]></description>
<content:encoded><![CDATA[<p>Navision <strong>C/AL</strong> can be quite monotonous to develop in &#8211; which is also one of its strengths &#8211; strength through simplicity, but sometimes one simply desires some power tools to get past the endless repetitive boiler-plate code.</p>
<p><strong>Microsoft .Net Framework, CLR, COM interop, C# and Lazy Evaluation (aka IEnumerable of T) to the rescue!</strong></p>
<p>The example I&#8217;ll show here is probably not the best one. I&#8217;ll be showing how to lazily enumerate files on the file system. Navision already has a special virtual table called the file table that serves to enumerate over the file system. Nevertheless, this example will show what you can do, and maybe you&#8217;ll prefer my approach, although minimizing dependencies on automations is of course desirable.</p>
<p>So, let&#8217;s get started here.</p>
<p>First we define an Navision version of the <strong>IEnumerable </strong>interface. This is straight-forward and is immensely useful for iteroperability between Navision and automations. It provides a very smooth iteration idiom.</p>
<p><code> </code></p>
<p><code></p>
<blockquote>
<pre>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo.IO
{
    using System.Runtime.InteropServices;

    [Guid("0BC2788B-A22E-4DF4-A04F-161E3A9EAFC4")]
    [ComVisible(true)]
    public interface ILinear
    {
        object Current { get; }

        bool MoveNext();

        void Reset();
    }
}</pre>
</blockquote>
<p></code></p>
<p>This simple interface provides a great deal of expressiveness due to its simplicity, generality and broad applicability.</p>
<p>In order to make use of this, an equal implementation class should be defined, it merely wraps around an IEnumerable&#60;object&#62;. This is left as an exercise for the reader.</p>
<p>Why IEnumerable of object you may ask? Because COM interop is not so happy about parametric polymorphism and generic types. That wohn&#8217;t be a problem in Navision though. The only problem is the limits around passing data to and from Navision where f.x. text is limited to 1024 characters. &#8211; But here you can again utilize the above type to indirectly pass around a large string wrapped in an ILinear.</p>
<p>Lazy Evaluation in C# 2.0 (yes, it&#8217;s so yesterday, but laziness never expires!) is our means to efficiently enumerate and traverse arbitrarily large file system trees. Here&#8217;s how it&#8217;s done.</p>
<p><code> </code></p>
<p><code></p>
<pre>        public ILinear GetFiles(string path, string pattern, bool recursive)
        {
            var result = (Linear)null;
            try
            {
                result = new Linear(LazyGetFiles(path, pattern, recursive));
            }
            catch (Exception) { }
            return result;
        }</pre>
<p></code></p>
<p>I&#8217;ll not show the definition of LazyGetFiles here, but you can find the basic technique many places on the Web, e.g.</p>
<ul>
<li><a href="http://weblogs.asp.net/whaggard/archive/2004/08/15/214864.aspx">http://weblogs.asp.net/whaggard/archive/2004/08/15/214864.aspx</a></li>
<li><a href="http://weblogs.asp.net/podwysocki/archive/2009/03/18/functional-net-laziness-becomes-you.aspx">http://weblogs.asp.net/podwysocki/archive/2009/03/18/functional-net-laziness-becomes-you.aspx</a></li>
</ul>
<p>I always wrap COM entry-points with exception handling to avoid crashing Navision should anything fail (using the most general exception class here). I found it a good practice to do this, in combination with access to the current exception state of the class, for logging unexpected run-time exceptions inside Navision.</p>
<p>It&#8217;s a bit painful to declare variables in Navision (you have to go through UI menus to do this, it&#8217;s not possible in pure text &#8211; although that may change in future versions of Navision) &#8211; the point of which is to say that if it were a bit less painful, maybe even with type-inference, one might instead return a <a href="http://en.wikibooks.org/wiki/Haskell/Hierarchical_libraries/Maybe">Maybe</a> value but we can use <strong>ISCLEAR</strong> from within Navision to detect null-values and therefore see if a failure occurred.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Batteries Included: Lazy Lists version 0.3]]></title>
<link>http://dutherenverseauborddelatable.wordpress.com/2008/05/18/batteries-included-lazy-lists-version-03/</link>
<pubDate>Sun, 18 May 2008 18:40:52 +0000</pubDate>
<dc:creator>yoric</dc:creator>
<guid>http://dutherenverseauborddelatable.wordpress.com/2008/05/18/batteries-included-lazy-lists-version-03/</guid>
<description><![CDATA[An updated version of the Lazy List module for OCaml has just been uploaded to Batteries Included an]]></description>
<content:encoded><![CDATA[<p style="text-align:justify;">An updated version of the Lazy List module for OCaml has just been uploaded to <a href="https://forge.ocamlcore.org/frs/?group_id=17">Batteries Included</a> and submitted to <a href="http://www.google.fr/url?sa=t&#38;ct=res&#38;cd=1&#38;url=http%3A%2F%2Fcode.google.com%2Fp%2Focaml-extlib%2F&#38;ei=v3cwSNH2MqPw-AL39cWIAg&#38;usg=AFQjCNEjWtWFbDXOLrRn-qxFA8-MlL8Ikg&#38;sig2=JV6e1hqE0-KmC5HpgwIeWQ">ExtLib</a>. See the release notes for more details.</p>
<p style="text-align:justify;">In addition, I am currently using this module to write a parser combinator library for OCaml. This library has reached early testing stage and will hopefully be added to Batteries Included soon.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Quelques mots de programmation paresseuse]]></title>
<link>http://dutherenverseauborddelatable.wordpress.com/2008/05/11/quelques-mots-de-programmation-paresseuse/</link>
<pubDate>Sun, 11 May 2008 20:20:22 +0000</pubDate>
<dc:creator>yoric</dc:creator>
<guid>http://dutherenverseauborddelatable.wordpress.com/2008/05/11/quelques-mots-de-programmation-paresseuse/</guid>
<description><![CDATA[Ces jours-ci, je travaille beaucoup avec et sur OCaml, que ce soit pour le projet ExtraPol (dont je]]></description>
<content:encoded><![CDATA[<p style="text-align:justify;">Ces jours-ci, je travaille beaucoup avec et sur OCaml, que ce soit pour le projet ExtraPol (dont je finirai bien par vous glisser quelques mots) ou pour <a href="https://forge.ocamlcore.org/mail/admin/index.php?group_id=17">Batteries Included</a> (la rénovation en cours de la bibliothèque standard de OCaml). En particulier, je viens de finaliser un module de <a href="https://forge.ocamlcore.org/frs/shownotes.php?release_id=12">gestion des listes paresseuses</a>. Paresseuses ? Oui, paresseuses.</p>
<p style="text-align:justify;">Attardons-nous un moment sur le concept de <em>paresse</em> en programmation.</p>
<p><!--more--></p>
<h2>En Java (ou C++ ou C# ou &#8230;)</h2>
<p style="text-align:justify;">Presque tous les langages de programmation permettent, de manière restreinte, de définir des expressions paresseuses, c&#8217;est-à-dire des expressions dont le résultat n&#8217;est calculé que s&#8217;il peut influencer l&#8217;exécution du programme. Ainsi, en Java, nous pourrons définir la méthode <code>isEquals</code> suivante :</p>
<pre class="brush: java; title: ; notranslate" title="">
bool isEquals(Object x)
{
  return x &amp;&amp; x.equals(myObject);
}
</pre>
<p style="text-align:justify;">Ici, au cours de l&#8217;exécution de cette fonction, <code>x.equals(myObject)</code> ne sera ffectivement évalué que si <code>x</code> n&#8217;est pas <code>null</code>. Java définit ainsi trois opérateurs paresseux <code>&#38;&#38;</code>, <code>&#124;&#124;</code> et <code>?:</code> : dans chacun des trois cas, à l&#8217;exécution du programme, la première opérande est évaluée avant de décider que faire de la deuxième (et de la troisième, dans le cas de <code>?:</code>). Ces constructions sont très utiles, mais sont loin de couvrir toutes les circonstances dans lesquelles la paresse peut s&#8217;avérer utile.</p>
<p style="text-align:justify;">Ainsi, imaginons un instant que nous souhaitons écrire une bibliothèque de journalisation, dont le rôle est d&#8217;enregistrer des messages dans un fichier au fur et à mesure de l&#8217;exécution du programme. Ajoutons une contrainte : les messages ne doivent être effectivement enregistrés que lorsque le journal est activé, par exemple parce que l&#8217;utilisateur est en mode de débogage :</p>
<pre class="brush: java; title: ; notranslate" title="">
void log(String s)
{
   if(LOG) stream.println(s);
}
</pre>
<p>La méthode <code>log</code> sera typiquement invoquée des centaines de fois durant l&#8217;exécution du code, sous la forme suivante :</p>
<pre class="brush: java; title: ; notranslate" title="">
void myFunction(int i, int j, int k)
{
   myLog.log(&quot;Entering myFunction(&quot;+i+&quot;, &quot;+j+&quot;, &quot;+j+&quot;)&quot;);
   //...
   myLog.log(&quot;Leaving myFunction()&quot;);
}
</pre>
<p style="text-align:justify;">Des centaines de fois, nous aurons donc besoin de calculer le résultat de <code>"Entering myFunction("+i+", "+j+", "+j+")"</code>, soit trois conversions d&#8217;entiers en chaînes de caractères, 6 concaténations de chaînes de caractères et un gaspillage de mémoire vive que nous pourrions éviter lorsque <code>LOG</code> est <code>false</code>. Comment faire pour éviter ce gaspillage ? La première possibilité consiste à exposer la valeur de <code>LOG</code> à tout le programme et à laisser le programmeur écrire plutôt</p>
<pre class="brush: cpp; title: ; notranslate" title="">
void myFunction(int i, int j, int k)
{
   if(LOG) myLog.log(&quot;Entering myFunction(&quot;+i+&quot;, &quot;+j+&quot;, &quot;+j+&quot;)&quot;);
   //...
   if(LOG) myLog.log(&quot;Leaving myFunction()&quot;);
}
</pre>
<p style="text-align:justify;">Malheureusement, cette transformation nous oblige à contaminer tout le programme avec ce champ <code>LOG</code>, au détriment de la lisibilité et de l&#8217;extensibilité. En C ou C++, on pourrait cacher ce <code>LOG</code> derrière une macro, cette fois au détriment du débogage, de la modularité et de la robustesse. En Java, si nous n&#8217;avons pas une telle possibilité, nous pouvons utiliser des classes anonymes  pour arriver aux mêmes fins :</p>
<p>Commençons par modifier notre bibliothèque de journalisation :</p>
<pre class="brush: java; title: ; notranslate" title="">
public interface LazyString
{
   public String toString();
}

void log(Object s)
{
   if(LOG) stream.println(s.toString());
}
</pre>
<p style="text-align:justify;">L&#8217;interface LazyString n&#8217;est guère contraignante : elle se contente de promettre que les objets qui l&#8217;implantent dispoent bien d&#8217;une méthode publique String toString(), qui servira à extraire de l&#8217;objet une chaîne de caractères. La différence avec ce qui précède est que nous pouvons nous débrouiller pour que la construction de la chaîne de caractères n&#8217;ait lieu qu&#8217;au moment où la méthode println est invoquée. En particulier, cette construction n&#8217;aura jamais lieu si <code>LOG</code> est false. Pour utiliser cette nouvelle version du journal, nous pourrons réécrire myFunction de la manière suivante :</p>
<pre class="brush: java; title: ; notranslate" title="">
void myFunction(int i, int j, int k)
{
   myLog.log(new LazyString() { public String toString() { return &quot;Entering myFunction(&quot;+i+&quot;, &quot;+j+&quot;, &quot;+j+&quot;)&quot; });
   //...
   myLog.log(&quot;Leaving myFunction()&quot;);
}
</pre>
<p style="text-align:justify;">Est-ce la fin de l&#8217;histoire ? Pas tout à fait. Pour le moment, en Java, nous ne pouvons pas améliorer la syntaxe lors de l&#8217;appel de <code>log</code> &#8212; en tant que langage, Java est connu pour sa lourdeur syntaxique. En l&#8217;absence d&#8217;un préprocesseur digne de ce nom, nous ne pourrons rien faire de ce côté-là. Par contre, nous pouvons nous attaquer à un autre problème, qui se posera dès que nous serons confrontés à une méthode <code>log</code> à peine peu plus complexe :</p>
<pre class="brush: java; title: ; notranslate" title="">
void log(Object s)
{
   if(LOG_TO_FILE) file_stream.println(s.toString());
   if(LOG_TO_WINDOW) text_pane.out.println(s.toString());
   if(LOG_TO_STATUSBAR) statusbar.setText(s.toString());
}
</pre>
<p style="text-align:justify;">Ici, <code>s.toString()</code> sera invoqué trois fois et calculera trois fois le même résultat. Pour un exemple aussi simple que le nôtre, ce n&#8217;est pas encore bien grave, mais on peut imaginer des contextes dans lesquels le calcul serait suffisamment long pour que ce délai soit inacceptable.</p>
<p style="text-align:justify;">Qu&#8217;à cela ne tienne, il suffit de réécrire <code>log</code> de manière à retenir la valeur de <code>s.toString()</code>. Voire mieux, nous pouvons encapsuler tout ceci dans une classe plus générique :</p>
<pre class="brush: java; title: ; notranslate" title="">
public interface Result&lt;T&gt;
{
   public T getValue();
}
public abstract class Lazy&lt;T&gt;
{
   private boolean computed = false;
   private T value = null;
   /**
    * Proceeds to the actual computation.
    * This method will only be called once.
    */
   protected abstract T value();
   public final synchronized T getValue()
   {
      if(computed == false)
      {
        value       = value();
        computed = true;
      }
      return value;
   }
}

public abstract class LazyString extends Lazy&lt;String&gt;
{
   public String toString()
   {
      return this.getValue();
   }
}
</pre>
<p>En modifiant <code>myFunction</code> pour utiliser cette nouvelle version de <code>LazyString</code>, nous obtenons :</p>
<pre class="brush: java; title: ; notranslate" title="">
void myFunction(int i, int j, int k)
{
   myLog.log(new LazyString() { protected String value() { return &quot;Entering myFunction(&quot;+i+&quot;, &quot;+j+&quot;, &quot;+j+&quot;)&quot; });
   //...
   myLog.log(&quot;Leaving myFunction()&quot;);
}
</pre>
<p style="text-align:justify;">Qu&#8217;avons-nous gagné ? Nous avons maintenant sous la main une interface Result&#60;T&#62; qui permet de représenter une opération. Si l&#8217;objet qui implante Result&#60;T&#62; est en fait un Lazy&#60;T&#62;, le calcul ne sera effectué que si son résultat est effectivement consulté. Si le résultat est consulté plusieurs fois (potentiellement par plusieurs threads différents), le calcul n&#8217;est toujours effectué qu&#8217;une seul fois.</p>
<p style="text-align:justify;">Nous venons d&#8217;ajouter une dose d&#8217;évaluation paresseuse à Java.</p>
<p style="text-align:justify;">Pour aller plus loin, regardons du côté de la programmation fonctionnelle &#8212; et des structures de données paresseuses.</p>
<h2>Du côté de la programmation fonctionnelle</h2>
<p>Commençons par réécrire en OCaml la première version de nos fonctions :</p>
<pre class="brush: python; title: ; notranslate" title="">
let log s = if should_log then output stream s
</pre>
<p style="text-align:justify;">Nous venons de définir, comme en Java, une fonction nommée log, qui accepte comme paramètre un argument s &#8212; ici, une chaîne de caractères. Le contenu de la fonction log instruit d&#8217;écrire s sur un certain flux stream, si une certaine valeur booléenne should_log est vraie. Comme en Java, nous invoquerons cette fonction depuis my_function, à l&#8217;aide de :</p>
<pre class="brush: python; title: ; notranslate" title="">
let my_function i j k =
  log (sprintf &quot;Entering my_function %i %i %i&quot; i j k);
  (* ... *)
  log &quot;Leaving my_function&quot;
</pre>
<p style="text-align:justify;">Jusque-là, à part les parenthèses et l&#8217;utilisation de la fonction <code>sprintf</code>, rien de bien différent. De nouveau, il est nécessaire de convertir i, j et k en chaînes de caractères et de procéder à quelques concaténations.</p>
<p style="text-align:justify;">À partir d&#8217;ici, comme en Java, nous pouvons définir équivalent de Lazy&#60;T&#62;, que nous appellerions probablement <code>'a lazy</code>, doté d&#8217;un constructeur qui acceptera en argument une fonction dont le résultat est un <code>'a</code>, etc. La transformation de notre code pour convertir log en appel paresseux est globalement similaire à ce que nous ferions en Java. De fait, tout ceci n&#8217;est pas nécessaire puisque puisque la programmation paresseuse est en fait une primitive du langage. Le mot-clé <code>lazy</code> introduit une expression de type <code>'a Lazy.t</code>, c&#8217;est-à-dire dont le résultat est de type <code>'a</code> et ne sera calculé que s&#8217;il est nécessaire. La fonction <code>force : 'a Lazy.t -&#62; 'a</code> permet alors de consulter le résultat d&#8217;une valeur ainsi mise en réserve, en la calculant au passage si nécessaire. De fait, notre version définitive ressemblera à</p>
<pre class="brush: python; title: ; notranslate" title="">
open Lazy
let log s =
  if should_log_1 then output stream_1 (force s);
  if should_log_2 then output stream_2 (force s);
  if should_log_3 then output stream_3 (force s)

let my_function i j k =
  log (lazy (sprintf &quot;Entering my_function %i %i %i&quot; i j k));
  (* ... *)
  log (lazy &quot;Leaving my_function&quot;)
</pre>
<p style="text-align:justify;">Notons au passage qu&#8217;il ne serait pas possible de réécrire directement lazy sous la forme d&#8217;une fonction OCaml. Pour réinventer <code>lazy</code>, il serait nécessaire de passer par Camlp4 ou d&#8217;accepter des notations légèrement plus lourdes.</p>
<h2>Et alors ?</h2>
<p style="text-align:justify;">Il va falloir que je vous avoue quelque chose : je me moque complètement de la fonction <code>log</code>. Dans la programmation paresseuse, le plus intéressant, c&#8217;est bien les structures de données.</p>
<p>Tenez, en Java, nous pouvons très bien redéfinir la notion d&#8217;itérateurs de la manière suivante :</p>
<pre class="brush: java; title: ; notranslate" title="">
public interface MyIterator&lt;T&gt;
{
  public Lazy&lt;MyIterator&lt;T&gt;&gt; next();
  public T value;
}
</pre>
<p>Un itérateur est ici un objet capable de contenir une valeur&#8230; et de renvoyer un autre itérateur, qui représente la suite de l&#8217;itération. On écrira de même en OCaml :</p>
<pre class="brush: python; title: ; notranslate" title="">
type 'a my_iterator = Iterator of 'a * 'a my_iterator Lazy.t
</pre>
<p>Complétons cette définition pour nous autoriser à construire des itérations <em>finies</em> :</p>
<pre class="brush: python; title: ; notranslate" title="">
type 'a node =
 &amp;#124; Nil
 &amp;#124; Cons of 'a * 'a lazy_list
type 'a lazy_list = ('a node) Lazy.t
</pre>
<p style="text-align:justify;">Nous venons de définir la notion de <em>liste paresseuse</em>. Une liste paresseuse est une valeur paresseuse qui, une fois évaluée, produit soit le résultat <code>Nil</code> (la liste vide), soit un résultat de la forme <code>Cons(h, t)</code> où <code>h</code> est une valeur et <code>t</code> est la suite de la liste paresseuse.</p>
<p style="text-align:justify;">À partir de cette définition, nous pouvons construire une fonction <code>range</code>, qui servira à représenter un intervalle d&#8217;entiers :</p>
<pre class="brush: python; title: ; notranslate" title="">
let rec range i j =
 if i &gt;= j then Nil
 else            range (i+1) j
</pre>
<p>Ainsi, en OCaml, <code>range 0 100000</code> calculera les nombres 0, 1, &#8230;, 100000 au fur et à mesure qu&#8217;ils seront demandés.</p>
<p style="text-align:justify;">À partir de là, nous pouvons définir les transformations habituelles sur les structures de données. Ainsi, pour convertir (paresseusement) une liste paresseuse en une autre, comme pour les listes habituelles, nous pouvons définir la fonction <code>map</code> :</p>
<pre class="brush: python; title: ; notranslate" title="">
let rec map f l = match force l with
  &amp;#124; Nil            -&gt; lazy Nil
  &amp;#124; Cons (h,t) -&gt; lazy Cons (f h, map f t)
</pre>
<p style="text-align:justify;">Cette fonction <code>map</code>, qui sera l&#8217;un des premiers outils que nous placerons dans notre bibliothèque de gestion des listes paresseuses, applique une fonction successivement à chaque élément d&#8217;une liste paresseuse, de manière à obtenir une nouvelle liste paresseuse. Pour doubler tous les éléments de notre intervalle précédent, nous écrirons donc</p>
<pre class="brush: python; title: ; notranslate" title="">
map (( * ) 2) (range 0 100000)
</pre>
<p style="text-align:justify;">De la même manière, nous pouvons définir le nécessaire pour filtrer les éléments d&#8217;une liste afin de n&#8217;en garder que ceux qui vérifient une propriété donnée, le tout sous la forme d&#8217;une fonction <code>filter</code>, qui rejoindra <code>map</code> dans notre bibliothèque standard.</p>
<pre class="brush: python; title: ; notranslate" title="">
let rec filter f l = match Lazy.force l with
  &amp;#124; Nil -&gt; lazy Nil
  &amp;#124; Cons(h,t) -&gt; lazy (Cons (f h, filter t))
</pre>
<p style="text-align:justify;">Et à ce prix-là, définissons une fonction <code>iter</code>, tout aussi standard, qui nous permettra d&#8217;appliquer une fonction impérative à tous les éléments d&#8217;une liste paresseuse, de la même manière que la boucle for de Python ou la nouvelle boucle for de Java :</p>
<pre class="brush: python; title: ; notranslate" title="">
let rec iter f l = match force l with
  &amp;#124; Nil            -&gt; ()
  &amp;#124; Cons (h,t) -&gt; f h; iter t
</pre>
<p style="text-align:justify;">En combinant tout ce qui précède, nous pouvons faire afficher les carrés parfaits de l&#8217;ensemble des nombres pairs des nombres de l&#8217;intervalle [0; 100000].</p>
<pre class="brush: python; title: ; notranslate" title="">
let is_square x =
  let y = int_of_float (sqrt (float_of_int x)) in
  x = y * y

iter print_int (filter is_square (map (( * ) 2) (range 0 100000)))
</pre>
<p style="text-align:justify;">Comme la liste n&#8217;est consultée qu&#8217;une seule fois, grâce à la magie de la paresse et du ramasse-miettes, tout ceci se fera fait sans avoir à allouer la mémoire vive nécessaire pour retenir tous les entiers entre 0 et 100000.</p>
<p style="text-align:justify;">Jusqu&#8217;ici, toutes les opérations que nous avons vues auraient pu être implantées, peut-être avec quelques difficultés, en utilisant des <em>itérateurs</em> ou des <em>générateurs</em>, tels que ceux que définissent les bibliothèques Java, C#, JavaScript, Python, OCaml etc. Tout comme les listes paresseuses, les itérateurs et générateurs permettent de représenter des suites d&#8217;informations qui ne seront effectivement calculées que lorsqu&#8217;elles seront effectivement consultées. Mais à la différence des listes paresseuses, les itérateurs/générateurs oublient les informations immédiatement après les avoir fournies. Si les itérateurs et générateurs sont très utiles &#8212; et probablement plus optimisés que les listes paresseuses pour les exemples précédents &#8212; leur champ d&#8217;application s&#8217;arrête dès que les données peuvent être utilisées plusieurs fois.</p>
<p style="text-align:justify;">Ainsi, considérons l&#8217;une des applications majeures des itérateurs/générateurs et des listes paresseuses : l&#8217;analyse de langages, et plus particulièrement l&#8217;analyse lexicale et syntaxique d&#8217;un code source. Le plus fréquemment, on commence par considérer le fichier d&#8217;entrée comme un itérateur/générateur de caractères. Un filtre, l&#8217;<em>analyseur lexical</em>, s&#8217;applique alors à cet itérateur pour le transformer en itérateur de <em>lexèmes</em> &#8212; c&#8217;est le rôle d&#8217;outils tels que Lex, Flex ou, aussi surprenant que cela puisse paraître, Sax. Ce deuxième itérateur est alors consommé par un <em>analyseur syntaxique</em>, dont le rôle est de produire un arbre de syntaxe abstraite, qui représentera le code source en mémoire vive &#8212; c&#8217;est, cette fois, le rôle d&#8217;outils tels que Bison, Yacc ou DOM. Ces derniers, ainsi que [presque tous] leurs concurrents, consultent à l&#8217;avance k lexèmes depuis l&#8217;itérateur de lexème, pour un certain k fixé lors de la conception de l&#8217;analyseur, émettent des hypothèses en partant de ces k lexèmes, et ne peuvent pas revenir en arrière, en cas d&#8217;erreur, de plus de k pas. À l&#8217;inverse, et de manière très schématique, les combinateurs de parseurs construits sur des listes paresseuses, tels que Parsec (pour Haskell) ou PLC (pour OCaml), ne sont pas limités par ces k lexèmes d&#8217;avance, puisqu&#8217;ils peuvent à volonté revenir en arrière dans la liste. Un élément ne disparaît de la liste paresseuse que lorsque sa valeur ne peut plus influencer l&#8217;exécution du programme. Cette conception à base de listes paresseuses se paye en termes de performances et de consommation de mémoire mais offre beaucoup plus de flexibilité, notamment la possibilité de construire ou de modifier dynamiquement des analyseurs syntaxiques.</p>
<p style="text-align:justify;">Avant de conclure sur la comparaison entre itérateurs et listes paresseuses, précisons brièvement qu&#8217;il est aisé de construire l&#8217;un par-dessus l&#8217;autre : un itérateur est une liste paresseuse qui oublie ses éléments au fur et à mesure qu&#8217;ils sont consommés, alors qu&#8217;une liste paresseuse est un itérateur qui retient ses éléments jusqu&#8217;à intervention du ramasse-miettes. Ainsi, dans la bibliothèque sur laquelle je travaille, la conversion d&#8217;une liste paresseuse en itération s&#8217;est écrite, jusqu&#8217;à une récente optimisation :</p>
<pre class="brush: python; title: ; notranslate" title="">
let enum l =
  let reference = ref l in
    Enum.from (fun () -&gt; match next !reference with
			 &amp;#124; Cons(x,t) -&gt; reference := t; x
			 &amp;#124; Nil          -&gt; raise Enum.No_more_elements )
</pre>
<p style="text-align:justify;">Dans cet extrait de code, nous commençons par déclarer une variable modifiable nommée <code>reference</code> et qui désignera initialement le premier élément de la liste. Nous définissons alors une fonction anonyme qui, lorsqu&#8217;elle sera appelée, renverra l&#8217;élément actuel désigné par <code>reference</code>, ou, si nous avons dépassé la fin de la liste, lancera une exception <code>Enum.No_more_elements</code> pour signaler que l&#8217;itérateur est terminé. La fonction <code>Enum.from</code> construit l&#8217;itérateur dont le comportement est donné par cette fonction.</p>
<p style="text-align:justify;">À l&#8217;inverse, pour convertir un itérateur en liste paresseuse, nous employons la fonction suivante :</p>
<pre class="brush: python; title: ; notranslate" title="">
let of_enum e =
  let rec aux () =
    lazy (match Enum.get e with
      &amp;#124;	Some x -&gt; Cons (x, aux () )
      &amp;#124; None    -&gt; Nil )
  in aux ()
</pre>
<p style="text-align:justify;">Dans l&#8217;extrait, nous commençons par définir une boucle que nous nommons <code>aux</code> et dons le contenu est paresseux. À chaque fois qu&#8217;un nouvel élément de la liste est consulté, nous consommons la valeur du prochain élément de notre itérateur. Si celui-ci existe, nous l&#8217;appelons <code>x</code>, et ce <code>x</code> constitue le prochain élément de notre liste, tandis que la suite de la liste sera donnée par le résultat de la prochaine invocation de la boucle <code>aux</code>. Dans le cas contraire, la liste est terminée.</p>
<h2>Références :</h2>
<ul>
<li>Pour plus de détails sur la distinction entre générateurs, itérateurs et listes paresseuses, je vous invite à consulter <a href="http://home.pipeline.com/~hbaker1/Iterator.html">Iterators: Signs of Weakness in Object-Oriented Languages, par Henry G. Baker</a>.</li>
<li>Pour plus de détails sur le module de listes paresseuses de Batteries Included, le code source est disponible <a href="https://forge.ocamlcore.org/frs/shownotes.php?release_id=12">sur OCaml Forge</a>. Le code source du module Enum, qui définit des itérateurs pour OCaml, est disponible avec le reste de la bibliothèque ExtLib, <a href="http://code.google.com/p/ocaml-extlib/">sur Google Code</a>.</li>
<li>Pour plus de détails sur la programmation paresseuse en OCaml, le <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Lazy.html">guide de référence</a> est à votre disposition.</li>
<li>Enfin, rendons à César ce qui appartient à César. Si l&#8217;évaluation paresseuse vous intéresse, vous êtes vivement encouragés à vous informer sur le langage de programmation Haskell, dans lequel toutes les évaluations sont paresseuses par défaut.</li>
</ul>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Batteries Included Preview: Lazy Lists]]></title>
<link>http://dutherenverseauborddelatable.wordpress.com/2008/05/10/batteries-included-preview-lazy-lists/</link>
<pubDate>Sat, 10 May 2008 20:17:47 +0000</pubDate>
<dc:creator>yoric</dc:creator>
<guid>http://dutherenverseauborddelatable.wordpress.com/2008/05/10/batteries-included-preview-lazy-lists/</guid>
<description><![CDATA[A quick note to inform that I have made available the first preview of a module for OCaml Batteries]]></description>
<content:encoded><![CDATA[<p style="text-align:justify;">A quick note to inform that I have made available the first preview of a  module for OCaml Batteries Included module: Lazy Lists for OCaml. This module adds the ability to manipulate lists composed of elements which are only computed whenever their value is first needed. In particular, such lists may be used as a more powerful replacement for streams &#8212; or to port interesting algorithms from Haskell.</p>
<p style="text-align:justify;">Code may be found <a href="https://forge.ocamlcore.org/frs/download.php/13/lazy_lists_0_2.tgz">here</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Functional Pearl: Trees]]></title>
<link>http://obfuscatedcode.wordpress.com/2008/02/16/functional-pearl-trees/</link>
<pubDate>Sun, 17 Feb 2008 03:31:40 +0000</pubDate>
<dc:creator>dbueno</dc:creator>
<guid>http://obfuscatedcode.wordpress.com/2008/02/16/functional-pearl-trees/</guid>
<description><![CDATA[[This post is Literate Haskell. If you copy the entire post into a file with a .lhs extension, you c]]></description>
<content:encoded><![CDATA[<p>[This post is Literate Haskell.  If you copy the entire post into a file with a <code>.lhs</code> extension, you can load up that file in your favorite Haskell Interpreter, and it should work.  Then you can test the functions mentioned herein.]</p>
<p>Given a binary tree (you know, a thing that&#8217;s either a leaf with some data or two branches, both of which are binary trees), can you compute a new binary tree with exactly the same structure, but with every leaf&#8217;s value replaced by the minimum value in the tree?</p>
<p>If you&#8217;re a programmer, of course you can.  One simple pass to find the minimum value in the tree, and another to replace each leaf with the minimum value.  Here is the data type and an implementation of this idea in Haskell.</p>
<pre>

&#62; data Tree a = Leaf a          -- The leaf holds data of any type.
&#62;             &#124; Branch (Tree a) (Tree a) deriving (Show)

&#62; replaceMin2 t = let m = findMin t
&#62;                 in propagate t m
&#62;   where
&#62;     findMin (Leaf m) = m
&#62;     findMin (Branch left right) = findMin left `min` findMin right

&#62;     propagate (Leaf _) m = Leaf m
&#62;     propagate (Branch left right) m = Branch (propagate left m)
&#62;                                              (propagate right m)

</pre>
<p>Simple, and clear.  Now, can you think of a way to do it in one pass?  You might consider making one pass in which (1) for each leaf, replace its value with a mutable cell that can hold a value, returning the value of the leaf, then (2) for each branch, recursively compute the min on the left and right.  At the end, you set the cell you gave to all the leaves to the value of the min you computed in this single pass, so that each leaf gets the value at once.</p>
<p>This is a good idea.  However, this will change the type of the new tree.  Instead of having a tree of integers, you&#8217;ll have a tree of cells-pointing-to-integers, and you&#8217;ll need another pass to get rid of them.</p>
<p>Here is a solution.  One pass.  Ponder it.</p>
<pre>

&#62; replaceMin :: Tree Int -&#62; Tree Int
&#62; replaceMin t = let (t', m) = rpMin (t, m) in t'

&#62; rpMin :: (Tree Int, Int) -&#62; (Tree Int, Int)
&#62; rpMin (Leaf a, m) = (Leaf m, a)
&#62; rpMin (Branch l r, m) = let (l', ml) = rpMin (l, m)
&#62;                             (r', mr) = rpMin (r, m)
&#62;                    in (Branch l' r', ml `min` mr)

</pre>
<p>Note how in <code>replaceMin</code> the variable <code>m</code> is both bound to the result of calling <code>rpMin</code> <i>and</i> as an argument to <code>rpMin</code>.  Totally insane.</p>
<h3>That Doesn&#8217;t Work</h3>
<p>I know; I said the same thing.  The contract of <code>rpMin</code> is that it consumes a tuple of the tree and the actual minimum value of the tree (!), and returns (1) the tree with the minimum value stuck in the right places, and (2) the actual minimum value.  If you&#8217;re used to imperative languages, or even functional languages without having used lazy evaluation, this contract is utter and complete nonsense.  In fact, it is strong grounds for doubting a programmer&#8217;s competence.</p>
<p>The reason it is nonsense is because <b>call-by-value</b> parameter passing is most programmer&#8217;s default mindset.  When a function is applied to its arguments, those arguments are computed down to some value of the appropriate type, and only then is the function invoked.  This is the function application semantics of many programming languages, such as Java, C, Perl, etc.</p>
<p>The function <code>replaceMin</code> depends upon a strange and wonderful semantics called <b>call-by-need</b> semantics.  In call-by-need semantics, when a function is invoked, the arguments are not evaluated.  Only when, and if, the body of the function <b>demands</b> one of the arguments are they actually turned into a value.  This fact makes <code>replaceMin</code> possible.  Since nothing in <code>rpMin</code> actually tests the value of <code>m</code> (e.g. by comparing it to 0 or something), but simply uses it, we are allowed to refer to a value which cannot even by computed until <code>rpMin</code> is finished.</p>
<p>This means the algorithm given above essentially implements the cells idea suggested before, with at least two advantages: (1) it&#8217;s pure, meaning there is no way to step on our toes by assigning the wrong thing at the wrong time; (2) it really requires only one traversal, and doesn&#8217;t change the type of our function.  It computes a new Tree of ints, just like the old one.</p>
<h3>Acknowledgements</h3>
<p>The function <code>replaceMin</code> and helper comes from <a href="http://www.cse.ogi.edu/pacsoft/projects/rmb/">http://www.cse.ogi.edu/pacsoft/projects/rmb/</a>, in particular under &#8220;Other Artifacts&#8221;, linked to by the bullet point, &#8220;Slides for a talk on the recursive do-notation.&#8221;  I have omitted a link to the PDF on purpose, so you&#8217;ll see all the cool stuff those people have done.</p>
<p><b>Update 18 Feb 2008</b>. As one person mentioned in the comments, this is quite obviously call-by-need, not call-by-name, semantics.  I have changed it in the post to avoid further confusion.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Functional Programming on .NET part 2]]></title>
<link>http://zerogradient.wordpress.com/2007/12/07/functional-programming-on-net-part-2/</link>
<pubDate>Fri, 07 Dec 2007 20:55:28 +0000</pubDate>
<dc:creator>Deen</dc:creator>
<guid>http://zerogradient.wordpress.com/2007/12/07/functional-programming-on-net-part-2/</guid>
<description><![CDATA[So most who read this aught to know what a prime number is, a number whose only factors are one and]]></description>
<content:encoded><![CDATA[<p>So most who read this aught to know what a prime number is, a number whose only factors are one and itself. This post is not on primes but does use them in a simple program which uses a simple algorithm to factor any given number. Now, many of you should know the difficulty in factoring numbers and how much of current cryptographic techniques rely on how hard the problem is.  The program I wrote was written as a benchmark between the languages F# and Nemerle. Primarily as an &#8220;expressioning&#8221; benchmark and then as an aside a note on speed.</p>
<p>The task was to write a program which takes an unbounded positive integer and outputs a list that is the decomposition of the number into its prime factors. I decided to leverage laziness to allow me to write a flexible and short implementation. As I will get to later neither of these languages support laziness in the true sense and hence corecursion (in the sense of the dual of recursion) was unavailable, disallowing techniques such as a lazy sieve. Firstly the theory.</p>
<p><strong>Theory</strong></p>
<p>Given some number n, there exists primes <img src='http://s0.wp.com/latex.php?latex=%28p_1%29%28p_2%29...%28p_k%29&amp;bg=ffffff&amp;fg=000&amp;s=0' alt='(p_1)(p_2)...(p_k)' title='(p_1)(p_2)...(p_k)' class='latex' /> such that <img src='http://s0.wp.com/latex.php?latex=n+%3D+%28p_1%29%28p_2%29...%28p_k%29&amp;bg=ffffff&amp;fg=000&amp;s=0' alt='n = (p_1)(p_2)...(p_k)' title='n = (p_1)(p_2)...(p_k)' class='latex' /> and the product <img src='http://s0.wp.com/latex.php?latex=%28p_1%29%28p_2%29...%28p_k%29&amp;bg=ffffff&amp;fg=000&amp;s=0' alt='(p_1)(p_2)...(p_k)' title='(p_1)(p_2)...(p_k)' class='latex' /> is unique to n. This is known as the Fundamental Theorem of Arithmetic or the unique factorization theorem. I will leave the <a href="http://www.komplexify.com/math/humor_pure/UsesOfFallacy.html">proof as an excercise to the reader</a>. A way to get to this is to divide n by its smallest factor &#62; 1. Store the factor and repeat on the quotient until we get to 1. Why the smallest factor? Because the smallest factor of n &#62; 1 must be prime. Why?</p>
<p>Suppose that this was false and smallest factor or least divisor of n, say a, was composite. Then we would have that there exists some b and some c such that a = b * c and that b &#62; 1 and b &#60; a (we are working with positive integers so if b = 1 then c = a, remember that b and c &#60; a). So b also divides n (consider n = a * d = b * c * d). But we stated earlier that a was the smallest divisor of n so by contradiction a must be prime.</p>
<p><em>So as an example we take n = 18.  we have a = 9 and d = 2. 3 divides 9 so it must divide 18 and 18 / 3 = 3 * 2. Now to continue. </em></p>
<p><em>Suppose we keep n = 18. We know 3 is its least divisor and its prime. so p1 = 3. We do 18/3 = 6.<br />
Next we find least divisor of 6 which is 2. so p2 = 2. Now we do 6/2 = 3. 3 is prime so 18 = 3 * 2 * 3.<br />
</em></p>
<p>So it seems to do this we need to know how to find the least divisor for a given number. Well we know that the least divisor of a number must always be prime. So if given n, to find ld of n we start from 2, check if n mod 2 = 0 and work up till we find a prime that divides n. So for 35 we&#8217;d go through 2, 3, and hit 5 as its least divisor. A way to stop unnecessary checks is to leverage the fact that if an integer n &#62; 1 is not divisible by any primes &#60; = <img src='http://s0.wp.com/latex.php?latex=%5Csqrt%7Bn%7D&amp;bg=ffffff&amp;fg=000&amp;s=0' alt='&#92;sqrt{n}' title='&#92;sqrt{n}' class='latex' /> then n is prime.</p>
<p>Let n = (p)(a). Let us suppose that p is the least divisor of n, we know it must be prime. Now suppose p &#62; <img src='http://s0.wp.com/latex.php?latex=%5Csqrt%7Bn%7D&amp;bg=ffffff&amp;fg=000&amp;s=0' alt='&#92;sqrt{n}' title='&#92;sqrt{n}' class='latex' /> then a &#62; <img src='http://s0.wp.com/latex.php?latex=%5Csqrt%7Bn%7D&amp;bg=ffffff&amp;fg=000&amp;s=0' alt='&#92;sqrt{n}' title='&#92;sqrt{n}' class='latex' /> since p &#60;= a (remember p is the smallest divisor). Then we have that <img src='http://s0.wp.com/latex.php?latex=n+%3D+p+%5Ccdot+a+%26%2362%3B+%28%5Csqrt%7Bn%7D%29%28%5Csqrt%7Bn%7D%29+%3D+n&amp;bg=ffffff&amp;fg=000&amp;s=0' alt='n = p &#92;cdot a &gt; (&#92;sqrt{n})(&#92;sqrt{n}) = n' title='n = p &#92;cdot a &gt; (&#92;sqrt{n})(&#92;sqrt{n}) = n' class='latex' /> which is a contradiction since it says n  &#62; n. So at least one of p or a must be less than <img src='http://s0.wp.com/latex.php?latex=%5Csqrt%7Bn%7D&amp;bg=ffffff&amp;fg=000&amp;s=0' alt='&#92;sqrt{n}' title='&#92;sqrt{n}' class='latex' />. We know p &#60;= a so we know that at least p &#60; <img src='http://s0.wp.com/latex.php?latex=%5Csqrt%7Bn%7D&amp;bg=ffffff&amp;fg=000&amp;s=0' alt='&#92;sqrt{n}' title='&#92;sqrt{n}' class='latex' />. This proves our proposition. Note also that since <img src='http://s0.wp.com/latex.php?latex=p+%5Cle+a%2C+p%5E2+%5Cle+p+%5Ccdot+a+%3D+n&amp;bg=ffffff&amp;fg=000&amp;s=0' alt='p &#92;le a, p^2 &#92;le p &#92;cdot a = n' title='p &#92;le a, p^2 &#92;le p &#92;cdot a = n' class='latex' />. We use that fact to lessen our checks.</p>
<p>The basic idea then is to define an infinite list of all natural numbers and the primes as those numbers which fail some primality test filtered out. We define that tests as any number which is its own least divisor. I will not explain the code in depth &#8211; there is plenty of documentation on both languages &#8211; this is mostly to show how easy it is to go from reasoning to implementation.</p>
<p><strong>Implementation.</strong></p>
<p>Below is the F# code which implements this functionality:</p>
<pre class="brush: python; title: ; notranslate" title="">open System

module Primes_f = 
    let (+:) a alList = LazyList.cons a alList

    let Z3 : bigint LazyList = LazyList.unfold (fun x -&gt; Some(x , x + 1I)) 3I 

    let rec least_denominator_byfactor l n = 
        match l with 
            LazyList.Cons(p,ps) -&gt; if n % p = 0I then 
                                        p
                                   elif p * p &gt; n then
                                        n
                                   else
                                        least_denominator_byfactor ps n  
                       
    let rec prime = function
        n when n  failwith &quot;Not positive Int&quot;
        &amp;#124; n when n = 1I -&gt; false
        &amp;#124; n when n &gt; 1I -&gt; least_denominator n = n
        &amp;#124; _ -&gt; failwith &quot;?&quot;
        
    and primes =  2I +: (LazyList.filter prime Z3)

    and least_denominator n = least_denominator_byfactor primes n
    
    let rec factors = function
        n when n  failwith &quot;Not positive Int&quot;
        &amp;#124; n when n = 1I -&gt; []
        &amp;#124; n when n &gt; 1I -&gt; let p = least_denominator n  
                           p :: (factors (n / p)) 
                           
        &amp;#124; _ -&gt; failwith &quot;?&quot;


</pre>
<p>To display: </p>
<pre class="brush: python; title: ; notranslate" title="">
    let dtm = DateTime.Now
    print_any (&quot;Time is: &quot; ^ dtm.ToString() )
    
    //99999988888776655423101   //let z = factors 999988710I//999998888877665542310I    
    let rnd = Random()                                        
    
    let rec Generate tx l = 
        match tx with
            0 -&gt; l
            &amp;#124; _ -&gt; let z = bigint.FromInt32 (rnd.Next(1000000,int.MaxValue))    
                   Generate (tx - 1) ( ( factors z )::l )
                                        
    let list_of_primefactors =  Generate 10000 []//factors 9876543210I  //3 mins 100,000 -  20sec 10,000 .05
    let dtm2 = DateTime.Now 
    let d = dtm2 - dtm
  
    let primes1 = List.filter (fun l -&gt; if List.length l = 1 then true else false) (list_of_primefactors)
    
    let probprimes = System.Convert.ToDouble( (List.length primes1)) / 1000.0
    
    
    List.map (fun c -&gt; print_any c ; System.Console.WriteLine (&quot;&quot;) ) primes1   
    print_any probprimes
    //print_any list_of_primefactors      
       
    System.Console.Write (&quot;\n\nTime is: &quot; ^ dtm2.ToString() ^ &quot; Took: &quot; ^ d.ToString() ^ &quot;\n&quot; )  
    System.Console.ReadLine ()


</pre>
<p>The F# code was pretty straightforward to implement. The language remains quite functional and I had a lazy list data structure which allowed semi-corecursion via unfold. Now the Nemerle code. Because of its more object-centricism (not a critique) I had to approach how I arranged the code a bit differently.</p>
<pre class="brush: cpp; title: ; notranslate" title="">  
module Number
    private least_denominator_byfactor(l : Primes,  n : decimal) : Decimal 
        def p =  l.prime
        
        if((p==3) &amp;&amp; (n%2 == 0))            
            2m
        else    
            if(n % p == 0)  
                p
            else if(p * p &gt; n)
                n
            else
                least_denominator_byfactor(l.next,n)          
            
    public least_denominator(n : Decimal) : Decimal 
        least_denominator_byfactor(Primes(3), n ) 
        
    public IsPrime(k: Decimal) : bool
        &amp;#124; n when n  throw ex(&quot;Not positive&quot;)
        &amp;#124; n when n == 1 =&gt; false
        &amp;#124; n when n == 2 =&gt; true
        &amp;#124; n when n % 2.0m == 0 =&gt; false
        &amp;#124; n when n &gt; 2 =&gt; (n == least_denominator(n))
   
    public next_prime (v : Decimal) : Decimal
        def ip = IsPrime(v + 1)
        match(ip) 
            &amp;#124; true =&gt; v + 1
            &amp;#124; false =&gt; next_prime(v + 1)
        
    public factors(number : Decimal) : list[Decimal]
            &amp;#124; n when n  throw ex(&quot;Not Positive&quot;)
            &amp;#124; n when n == 1 =&gt; []
            &amp;#124; n when n &gt; 1 =&gt; def p = least_denominator(n) ; p :: factors(n/p)          

class Primes
    public prime : Decimal
    public next : LazyValue [Primes]
            
    public this (p : Decimal) 
        prime = p
        next = lazy (Primes (Number.next_prime(p)))


</pre>
<p>To display:
<pre class="brush: cpp; title: ; notranslate" title="">  
module Program
    Main() : void
    
        def dtm = DateTime.Now 
        WriteLine($&quot;Time now is: $dtm&quot;) 
                  // 9998876655423101
        //Test Nums: 99998877665542310
        def rnd = Random()
        
        def Generate(tx, l = [])
            match(tx)
                &amp;#124; 0 =&gt; l 
                &amp;#124; _ =&gt; Generate(tx - 1, Number.factors( rnd.Next(1000000, int.MaxValue) )::l) 
            
        def list_of_primefactors = Generate(152)//Number.factors(9766427) 
       
        def dtm2 = DateTime.Now       
        
        foreach(pfactors in list_of_primefactors)
            foreach(num in pfactors)
               Write($&quot;$num &amp;#124; &quot;) 
            WriteLine(&quot;&quot;)       */
        
        WriteLine($&quot;Time Now is: $dtm2, Took $(dtm2 - dtm)&quot;)
        ReadLine()
</pre>
<p>While for example in the F# code I had only functions and general functionality I had to package the code into appropriate classes in nemerle and to have behaviour sort of baked into those data types (for example I could not unfold into a generic list of primes, I had to build a next mechanism into the lazy prime class). The nemerle implementation (algorithim not language) is quite a bit less inefficient. But this is because I did not really redress the design to go with objects. For example in F# I could afford mutual recursion since F# has light weight &#60;fast&#62; functions and has the caveat that the lazy list caches its data.</p>
<p>In Nemerle the Primality check in IsPrime requires more and more objects to be created until the test is passed (note the circularity wher ld looks for a next prime which in turn calls ld to find if its prime) so it bogs down quite quickly. Indeed for small numbers (less than 10 digits) the performance is quite close &#8211; implying that the actual languages are not far apart in speed. Nonetheless the rate of increase in time usage for Nemerle is much steeper (by a factor of ~14 before change but dropping to near F#&#8217;s after for single iterations) than for F# due to the object thrashing I was doing. For example by merely injecting the following code</p>
<pre class="brush: cpp; title: ; notranslate" title="">
private ldf(k : decimal,n : decimal) : decimal
        match(k) 
            &amp;#124; m when n % m == 0 =&gt; m
            &amp;#124; m when m * m &gt; n =&gt; n
            &amp;#124; _ =&gt; ldf(k + 1, n) 

private ld(n : decimal) : decimal
        ldf(2,n)  </pre>
<p>and replacing the appropriate function in IsPrime, factoring 99998877665542310 went from taking 25 seconds to 3 seconds. A similar injection to F# increased the speed from 2 seconds to 8. F# certainly benefits from the caching in its Lazy list implementation. Both languages are eagerly evaluated except in small localized places. In effect the evaluation is more delayed than it is lazy in the true sense that one would find in Haskell. Thus for example this:</p>
<p><strong>let rec sieve function = LazyList.Cons(z, zs) -&#62; z +: sieve (LazyList.filter (fun n -&#62;  (n % z) &#60;&#62; 0I) zs </strong></p>
<p>would fail to terminate when given sieve Z3, while similar code in Haskell knows where to stop evaluation.</p>
<p><strong>Speed</strong></p>
<p>As Noted earlier the F# code was fairly fast (helped, I suspect because of it caching, thus larger numbers benefited from previous computations and in having to do less work. One can really tell over multiple iterations where past iterations aid future ones. For example it took 3 minutes to factor 100,000 numbers between, 1,000,000 and 2^32. While it takes 15 secs (down from ~ 60 secs) in Nemerle to factor 120 nums, it takes F# 3 secs. In the next post I will post on Visual Studio integration, some graphs and data and improvements in the arrangement of code and primality testing for Nemerle.</p>
<p>One note is that F# sometimes generates confusing error messages. This error was due to using an int in place of a bigint i.e. n % 0 vs n % 0I. <em>Error 1 Type error in the use of the overloaded operator &#8216;( % )&#8217;. No operator &#8216;%&#8217; (full name &#8216;op_Modulus&#8217;) supported by the type &#8216;bigint&#8217; matches the argument types. See also C:\projects\prime\prime\prime.fs(12,23)-(12,24). See also </em>. Note the nice type system at work =)</p>
<p>As well, sometimes when you dont define your pattern matching cases properly it fails to build yet gives no error. Still some ways to go before being commercial. But hope it doesnt sell out when it does.</p>
<p>Interestingly .NET had no built in arbitrary precision integer data type (had because they just put it in for 3.5). F# does but Nemerle had to use decimal. Note though that to change I but have to rename type annotations. The code is general. Excluding the modules and classes Nemerle code and F# are very much on par.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Laziness is a virtue (in programming)]]></title>
<link>http://muharem.wordpress.com/2007/05/27/laziness-is-a-virtue-in-programming/</link>
<pubDate>Sun, 27 May 2007 08:44:40 +0000</pubDate>
<dc:creator>muharem</dc:creator>
<guid>http://muharem.wordpress.com/2007/05/27/laziness-is-a-virtue-in-programming/</guid>
<description><![CDATA[Introduction One of the things I really appreciate about Python is that it allows me to explore diff]]></description>
<content:encoded><![CDATA[<h3>Introduction</h3>
<p>One of the things I really appreciate about Python is that it allows me to explore different programming styles. When I started with Python (coming from a C/C++/Java background) I would mostly use procedural style constructs.</p>
<p>These days, however, I am usually inclining towards a more <a href="http://www.amk.ca/python/writing/functional">functional pogramming style</a>.</p>
<p>One of the key books that swayed me towards the latter was Mark Pilgrim&#8217;s <a href="http://www.diveintopython.org/">&#8220;Dive Into Python&#8221;</a>, one of the best (technical) books I have read so far. If you haven&#8217;t come across it yet, you should definitely take a look at it.</p>
<p>Another Python gem you may want to check out while experimenting with functional programming ideas is the <a href="http://docs.python.org/lib/itertools-functions.html"><span style="font-family:Courier;font-weight:bold;">itertools</span></a> module.</p>
<h3>Example</h3>
<p>In the brief <a href="http://hrnjad.net/src/8/evaltest2.py.html">section of code</a> that follows below I am contrasting the procedural versus the functional pogramming style through an example in which I am interested in obtaining the first in a (potentially large) range of numbers whose 8th root is an integer.</p>
<pre>
 <span style="color:#7f7f7f;"> 1 </span><span style="color:#cd00cd;">from</span> math <span style="color:#cd00cd;">import</span> (pow, modf)
 <span style="color:#7f7f7f;"> 2 </span><span style="color:#cd00cd;">from</span> itertools <span style="color:#cd00cd;">import</span> dropwhile
 <span style="color:#7f7f7f;"> 3 </span>
 <span style="color:#7f7f7f;"> 4 </span><span style="color:#00008b;font-weight:bold;">def</span> <span style="color:#008b8b;">calculate</span>(x):
 <span style="color:#7f7f7f;"> 5 </span>    &#34;&#34;&#34;<span style="color:#008b00;">calculates the 8th root of the number &#39;x&#39;</span>&#34;&#34;&#34;
 <span style="color:#7f7f7f;"> 6 </span>    <span style="color:#00008b;font-weight:bold;">return</span>(pow(x, 0.125))
 <span style="color:#7f7f7f;"> 7 </span>
 <span style="color:#7f7f7f;"> 8 </span><span style="color:#00008b;font-weight:bold;">def</span> <span style="color:#008b8b;">wanted</span>(v):
 <span style="color:#7f7f7f;"> 9 </span>    &#34;&#34;&#34;<span style="color:#008b00;">integer check: returns &#39;True&#39; if fractional part of a number is 0</span>&#34;&#34;&#34;
 <span style="color:#7f7f7f;">10 </span>    <span style="color:#00008b;font-weight:bold;">return</span>(<span style="color:#00008b;font-weight:bold;">not</span> modf(v)[0])
 <span style="color:#7f7f7f;">11 </span>
 <span style="color:#7f7f7f;">12 </span><span style="color:#00008b;font-weight:bold;">def</span> <span style="color:#008b8b;">unwanted</span>(v):
 <span style="color:#7f7f7f;">13 </span>    &#34;&#34;&#34;<span style="color:#008b00;">returns &#39;False&#39; if fractional part of a number is &#62; 0</span>&#34;&#34;&#34;
 <span style="color:#7f7f7f;">14 </span>    <span style="color:#00008b;font-weight:bold;">return</span>(modf(v)[0])
</pre>
<p>The lines 16-25 show a procedural style function using a loop and related control flow constructs to get the job done.</p>
<pre>
 <span style="color:#7f7f7f;">16 </span><span style="color:#00008b;font-weight:bold;">def</span> <span style="color:#008b8b;">proceduralStyle</span>(f, t):
 <span style="color:#7f7f7f;">17 </span>    &#34;&#34;&#34;
 <span style="color:#7f7f7f;">18 </span><span style="color:#008b00;">    finds the first in the range of numbers [f..t[ whose 8th root is an</span>
 <span style="color:#7f7f7f;">19 </span><span style="color:#008b00;">    integer; procedural style</span>
 <span style="color:#7f7f7f;">20 </span><span style="color:#008b00;">    </span>&#34;&#34;&#34;
 <span style="color:#7f7f7f;">21 </span>    <span style="color:#00008b;font-weight:bold;">for</span> x <span style="color:#00008b;font-weight:bold;">in</span> xrange(f, t):
 <span style="color:#7f7f7f;">22 </span>        v = calculate(x)
 <span style="color:#7f7f7f;">23 </span>        <span style="color:#00008b;font-weight:bold;">if</span> wanted(v): <span style="color:#00008b;font-weight:bold;">break</span>
 <span style="color:#7f7f7f;">24 </span>    <span style="color:#00008b;font-weight:bold;">else</span>: v = None
 <span style="color:#7f7f7f;">25 </span>    <span style="color:#00008b;font-weight:bold;">return</span>(v)
</pre>
<p>The functional style solution (see lines 27-34 below) uses the <code>dropwhile()</code> method (from the <a href="http://docs.python.org/lib/itertools-functions.html"><span style="font-family:Courier;font-weight:bold;">itertools</span></a> module) to get rid of any unwanted initial values (line 32).</p>
<p>Please note also how a <a href="http://en.wikipedia.org/wiki/List_comprehension#In_Python">generator expression</a> (as opposed to normal list comprehension) is used (on line 32) to achieve <a href="http://en.wikipedia.org/wiki/Lazy_evaluation">lazy evaluation</a> behaviour.</p>
<p>The syntactical differences are minute (parentheses versus square brackets) but the effects are huge.</p>
<p>A <a href="http://docs.python.org/tut/node7.html#SECTION007140000000000000000">normal list comprehension</a> will construct the entire list (and perform any calculations needed in the process) before completing. A <a href="http://www.python.org/dev/peps/pep-0289/">generator expression</a> on the other hand is comparable to an iterator, values are returned in piecemeal fashion and calculations are performed only as needed.</p>
<pre>
 <span style="color:#7f7f7f;">27 </span><span style="color:#00008b;font-weight:bold;">def</span> <span style="color:#008b8b;">functionalStyle</span>(f, t):
 <span style="color:#7f7f7f;">28 </span>    &#34;&#34;&#34;
 <span style="color:#7f7f7f;">29 </span><span style="color:#008b00;">    finds the first in the range of numbers [f..t[ whose 8th root is an</span>
 <span style="color:#7f7f7f;">30 </span><span style="color:#008b00;">    integer; functional style</span>
 <span style="color:#7f7f7f;">31 </span><span style="color:#008b00;">    </span>&#34;&#34;&#34;
 <span style="color:#7f7f7f;">32 </span>    r8iter = dropwhile(unwanted, (calculate(x) <span style="color:#00008b;font-weight:bold;">for</span> x <span style="color:#00008b;font-weight:bold;">in</span> xrange(f, t)))
 <span style="color:#7f7f7f;">33 </span>    <span style="color:#00008b;font-weight:bold;">try</span>: <span style="color:#00008b;font-weight:bold;">return</span>(r8iter.next())
 <span style="color:#7f7f7f;">34 </span>    <span style="color:#00008b;font-weight:bold;">except</span> StopIteration: <span style="color:#00008b;font-weight:bold;">return</span>(None)
</pre>
<p>Finally, by experimenting with the <a href="http://hrnjad.net/src/8/evaltest2.py">source code</a> we can see that <a href="http://en.wikipedia.org/wiki/Lazy_evaluation">lazy evaluation</a> is in effect for the <code>functionalStyle()</code> function. It returns straightaway with the result anticipated (256 is the first number in the range whose 8th root is an integer (2)).</p>
<pre>
 <span style="color:#7f7f7f;"> 1 </span>bbox33:published $ <span style="font-weight:bold;">python</span>
 <span style="color:#7f7f7f;"> 2 </span>Python 2.4.4 (#1, May 22 2007, 13:30:14)
 <span style="color:#7f7f7f;"> 3 </span>[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
 <span style="color:#7f7f7f;"> 4 </span>Type &#34;help&#34;, &#34;copyright&#34;, &#34;credits&#34; or &#34;license&#34; for more information.
 <span style="color:#7f7f7f;"> 5 </span> &#62;&#62;&#62; <span style="font-weight:bold;">import evaltest2</span>
 <span style="color:#7f7f7f;"> 6 </span> &#62;&#62;&#62; <span style="font-weight:bold;">from time import asctime as t</span>
 <span style="color:#7f7f7f;"> 7 </span> &#62;&#62;&#62; <span style="font-weight:bold;">print t(); evaltest2.functionalStyle(2, 50000000); print t()</span>
 <span style="color:#7f7f7f;"> 8 </span>Sun May 27 10:33:18 2007
 <span style="color:#7f7f7f;"> 9 </span>2.0
 <span style="color:#7f7f7f;">10 </span>Sun May 27 10:33:18 2007
 <span style="color:#7f7f7f;">11 </span> &#62;&#62;&#62; <span style="font-weight:bold;">print t(); evaltest2.proceduralStyle(2, 50000000); print t()</span>
 <span style="color:#7f7f7f;">12 </span>Sun May 27 10:33:30 2007
 <span style="color:#7f7f7f;">13 </span>2.0
 <span style="color:#7f7f7f;">14 </span>Sun May 27 10:33:30 2007
</pre>
]]></content:encoded>
</item>

</channel>
</rss>
