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

<channel>
	<title>www.hans-eric.com &#187; D Programming Language</title>
	<atom:link href="http://www.hans-eric.com/category/d-programming-language/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.hans-eric.com</link>
	<description>Hans-Eric Grönlund on software development</description>
	<lastBuildDate>Sat, 01 Oct 2011 12:07:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Functional D: Is Transitive Const Fundamental?</title>
		<link>http://www.hans-eric.com/2008/07/30/functional-d-is-transitive-const-fundamental/</link>
		<comments>http://www.hans-eric.com/2008/07/30/functional-d-is-transitive-const-fundamental/#comments</comments>
		<pubDate>Wed, 30 Jul 2008 11:50:56 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[D Programming Language]]></category>
		<category><![CDATA[Functional D]]></category>
		<category><![CDATA[functional programming]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/?p=124</guid>
		<description><![CDATA[As I&#8217;ve mentioned before, a pure functional subset is forming in the D Programming Language. According to the creators of D, transitive const is a key feature to make this work. The future of programming will be multicore, multithreaded. Languages that make it easy to program them will supplant languages that don&#8217;t. Transitive const is [...]]]></description>
			<content:encoded><![CDATA[<p>As <a title="The Functional Subset of D" href="http://www.hans-eric.com/2008/05/20/the-functional-subset-of-d/">I&#8217;ve mentioned before</a>, a pure functional subset is forming in the D Programming Language. According to the creators of D, transitive const is a key feature to make this work.</p>
<blockquote><p>The future of programming will be multicore, multithreaded. Languages that 	make it easy to program them will supplant languages that don&#8217;t. Transitive const is key to bringing D into this paradigm. [...] C++ cannot be retrofitted to supporting multiprogramming in a manner that makes it accessible. D isn&#8217;t there yet, but it will be, and transitive const will be absolutely fundamental to making it work.</p></blockquote>
<p><small>[<a title="Const(FAQ)" href="http://www.digitalmars.com/d/2.0/const-faq.html#transitive-const">Quote from the D website</a>]</small></p>
<h3>What is transitive const?</h3>
<p>Just a quick explanation for those of us who doesn&#8217;t have academic terms in close memory. Transitivity is a property of some binary relations, for example equality:</p>
<p><em>if A = B and B = C, then A = C</em></p>
<p>Applied to the concept of const it means, simply put, that anything reachable from a const type is also a const. So, for a declaration <em>const int **p</em>, <em>p</em> is const, as well as <em>*p</em> and <em>**p</em>.<br />
The same is true in the case of composite types:</p>
<pre class="brush: d; title: ; notranslate">
class A {
  int f;

  void set_f(int a_value) {
    f = a_value;
  }
}

const A a = new A();
a = new A(); // error
a.a = 2; // error
a.set_a(2); // error
</pre>
<p>All three reassignments above result in compiler errors due to the fact that a is const, and anything reachable from it is also const.</p>
<h3>Why does it matter?</h3>
<p>So, in what way is transitive const fundamental to concurrent programming? Well, it isn&#8217;t. What Walter Bright and his companions refer to is the fact that pure functional programming is thread-safe by design. That is, in a pure functional language the result of a function is solely dependent on its arguments. Thus, in a code like this:</p>
<pre class="brush: d; title: ; notranslate">
val = some_func( a(), b(), c() );
</pre>
<p>functions a(), b() and c() can be safely executed concurrently in a multi-core architecture; Nothing a(), b() or c() does can affect each others results. This is not the case for imperative languages that builds on the notion of mutable and global state. With mutable state comes hidden side-effects (a(), b() or c() could change common data and cause raise conditions) that complicates multi-thread programming so much.</p>
<p>What the people behind D tries to do is to create a pure functional subset within the language. I like to refer to it as Functional D. Such a subset would allow us to write code that is thread-safe by default, all you have to do is to write Functional D code. The compiler would then be able to chisel out the functional code and fully utilize the advantages of functional programming.</p>
<h3>Immutable data and pure functions <em>are</em> fundamental</h3>
<p>To make this work we need a way to make data immutable and a way to shut down access to the global state. In D you use the <em>invariant</em> keyword to create immutable data. The <em>pure</em> keyword is used to mark functions that may only take invariant arguments, no access to the global state, and that may only invoke other pure functions. (As of this writing, the semantics of the pure keyword is not yet implemented).</p>
<pre class="brush: d; title: ; notranslate">
int g = 0;

pure int pure_func(invariant int a) {
  a = 0; // error, a is invariant
  g = 1; // error, can't write to global g
  writefln(a); // error, writefln is not pure
  return g + a; // error, can't read global g
}
</pre>
<p>How does transitive const fit into all of this? To use the intuitive definitions from Andrei Alexandrescu&#8217;s <a title="Grafting Functional Support on Top of an Imperative Language" href="http://www.digitalmars.com/d/2.0/accu-functional.pdf">slides on the functional subset of D</a>:</p>
<blockquote>
<ul>
<li>const(T) x: I can’t modify x or anything reachable from it</li>
<li>invariant(T) x: Nobody can modify x or anything reachable from it</li>
</ul>
</blockquote>
<p>Const is not strong enough to be used in the functional subset (which depends on truly immutable data), but it has one application that could be important. From Walter Bright at the D newsgroup:</p>
<blockquote><p>Const allows you to reuse code that works on invariants to work with<br />
mutables, too.</p></blockquote>
<h3>How usable is const to the functional subset?</h3>
<p>Const can be used to write code that works with data from both the imperative (mutable) and the functional (immutable) subsets. For example, the print function below.</p>
<pre class="brush: d; title: ; notranslate">
void print(const int a) {
  writefln(a);
}

const int a = 1;
print(a); // ok

invariant int b = 2;
print(b); // ok

print(3); // ok
</pre>
<p>The reason this works is that invariants and immutable data is implicitly converted to const when necessary. One can question how useful this would be in practice though, the print function above would not be invokable from the functional subset (which would require it to be pure).</p>
<p>My conclusion is that although it may very well be important, transitive const is not &#8220;absolutely fundamental to making it work.&#8221; Transitive invariant, on the other hand, is.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2008/07/30/functional-d-is-transitive-const-fundamental/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>The Functional Subset of D</title>
		<link>http://www.hans-eric.com/2008/05/20/the-functional-subset-of-d/</link>
		<comments>http://www.hans-eric.com/2008/05/20/the-functional-subset-of-d/#comments</comments>
		<pubDate>Tue, 20 May 2008 12:00:11 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[D Programming Language]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/?p=117</guid>
		<description><![CDATA[As I wrote about in an earlier post, the future of D lies in the field of functional programming. More specifically, what the creators of D are trying to do, is to construct a pure functional subset that can be utilized within the otherwise imperative language. Let&#8217;s take a closer look at that functional subset [...]]]></description>
			<content:encoded><![CDATA[<p>As I <a title="The Future of D is Functional" href="http://www.hans-eric.com/2008/04/16/the-future-of-d-is-functional/">wrote about in an earlier post</a>, the future of D lies in the field of functional programming. More specifically, what the creators of D are trying to do, is to construct a pure functional subset that can be utilized within the otherwise imperative language.</p>
<p>Let&#8217;s take a closer look at that functional subset that is taking form in the experimental 2.0 version of D.</p>
<h3>Immutable data</h3>
<p>The most fundamental difference between a purely functional language and an imperative one is how they treat data. Many of us are used to think of data in terms of state, where variables can be changed through assignments. But in a functional program there are no states. There are only constant values and functions that operate on them.</p>
<p>In D, immutability is achieved with the <em>invariant</em> keyword, either as a storage class:</p>
<pre class="brush: d; light: true; title: ; notranslate">
invariant int i = 3;
</pre>
<p>or as a type constructor:</p>
<pre class="brush: d; light: true; title: ; notranslate">
invariant(int) i = 3;
</pre>
<h3>Transitive invariance</h3>
<p>The side-effect free nature that comes with immutable data has some great advantages.  For one thing it simplifies testing since the result of a function only depends on its input. There are also some optimizations that can be done by the compiler, but the biggest advantage is that programs written in this way are thread-safe by default.</p>
<p>To take advantage of these things the compiler needs to be able to trust the immutability of our data. This is where transitivity comes in.  In D, invariance is transitive, which basically means that no data reachable from an invariant reference can be changed. Here&#8217;s an example.</p>
<pre class="brush: d; title: ; notranslate">
int ga = 2; // mutable

struct A {
  int *p = &amp;amp;ga; // pointer to mutable
}

invariant(A) a; // a is immutable
A b; // b is mutable

// invariant is transitive
a = b; // ERROR, a is immutable
a.p = null; // ERROR, a.p is immutable
*a.p = 3; // ERROR, data pointed to by a.p is also immutable
</pre>
<h3>Garbage collection</h3>
<p>Since data must never change in a functional program, and consequently must not be destroyed while the data is in use, it&#8217;s usually a good idea for a functional language to utilize automatic memory management. Like most functional languages, D features garbage collection (<a title="Managing Object Lifetimes in D" href="http://www.hans-eric.com/2008/02/07/managing-object-lifetimes-in-d/">alongside with explicit memory management</a>.)</p>
<h3>Higher class functions</h3>
<p>In order to do anything interesting in a purely functional language you need higher order functions, or &#8211; in other words &#8211; the ability to send functions as arguments to other functions. For this we can use the function pointers (or delegates for methods and nested functions).</p>
<p>As an example, let&#8217;s say that we want to create a function that calculates the sum of two adjacent Fibonacci numbers. Here&#8217;s one way to do that.</p>
<pre class="brush: d; title: ; notranslate">
int nth_fib(int n) {
  if(n == 0) return 0;
  if(n == 1) return 1;
  return nth_fib(n-1) + nth_fib(n-2);
}

int add_next_fib(int n) {
  return nth_fib(n) + nth_fib(n+1);
}
</pre>
<p>Now, let&#8217;s say that we want to do the same operation on a different sequence, for example natural numbers. Well, we could use the good old copy and paste but that isn&#8217;t very <a title="Don't Repeat Yourself" href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a>. Let&#8217;s make add_next a higher order function instead so that it could be used with any sequence function.</p>
<pre class="brush: d; title: ; notranslate">
int add_next(int n, &lt;em&gt;int function(int) nth&lt;/em&gt;) {
  return nth(n) + nth(n+1);
}

int i = add_next(3, &amp;amp;nth_fib);
// i is 8 (3+5)
</pre>
<p>Now, we can write any sequence function we want and have add_next apply it.</p>
<pre class="brush: d; title: ; notranslate">
// Sequence function for natural numbers
int nth_nat(int n) {
  return n;
}

int i = add_next(3, &amp;amp;nth_nat);
// i is 7 (3+4)
</pre>
<p>Note: For methods and nested functions, the keyword <em>function</em> is replaced with the keyword <em>delegate</em>, otherwise it&#8217;s the same syntax.</p>
<h3>Closures</h3>
<p>Closures is another indispensable feature of functional languages. In short, it&#8217;s the ability to extract a function pointer for later use, and when invoked the function will still have access to the context in which it was created, even though that context has gone out of scope.</p>
<p>In D, closures are created with the <em>delegate</em> keyword.</p>
<pre class="brush: d; title: ; notranslate">
int delegate() create_closure() {
  int x = 3;

  int f() {
    return x;
  }

  return &amp;amp;f;
}

int delegate() a_closure = create_closure();
int i = a_closure();
// i is 3
</pre>
<p>Note that the extracted function f (referenced by the a_closure variable) accesses the local variable x, although it has gone out of scope at the time of execution. D got this ability with the 2.07 version, before that <a href="http://www.hans-eric.com/2007/09/11/d-doesnt-have-real-closures/">it didn&#8217;t have real closures</a>.</p>
<h3>Currying</h3>
<p>Closures provide an easy way to do currying, which is common in functional languages. Simply put, currying is a technique where functions take a general function and return a new, more specialized one.</p>
<p>For instance, we could curry our add_next function in our previous example and create a specialized version of it, say add_next_fib (and thus get back to where we started).</p>
<pre class="brush: d; title: ; notranslate">
int delegate(int) curry_add_next(int function(int) nth) {
  int curry_f(int n) {
    return add_next(n, nth);
  }
  return &amp;amp;curry_f;
}

int delegate(int) add_next_fib = curry_add_next(&amp;amp;nth_fib);
int i = add_next_fib(5);
// i is still 8
</pre>
<h3>Pure functions</h3>
<p>These features are all we need to write purely functional code, but in order to take full advantage of the functional programming paradigm some major things remain unsolved.</p>
<p>For one thing, the compiler needs to know whether or not our code is functional in order to apply possible optimizations. The easiest way to do this is to give the programmer a keyword to tell the compiler she wishes purity, and then have the compiler enforce it. In D this is the purpose of the <em>pure storage class</em>.</p>
<pre class="brush: d; title: ; notranslate">
pure int a_pure_square_function(invariant(int) x) {
  return x * x;
}
</pre>
<p>A pure function must not access non-invariant data, and may not invoke other non-pure functions. As per D2.13, the pure storage class has not had its semantics implemented and are therefore not enforcing purity. I sense this is not a trivial matter, so it may take some time before we have it.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2008/05/20/the-functional-subset-of-d/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>The Future of D is Functional</title>
		<link>http://www.hans-eric.com/2008/04/16/the-future-of-d-is-functional/</link>
		<comments>http://www.hans-eric.com/2008/04/16/the-future-of-d-is-functional/#comments</comments>
		<pubDate>Wed, 16 Apr 2008 10:33:44 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[D Programming Language]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[functional programming]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/2008/04/16/the-future-of-d-is-functional/</guid>
		<description><![CDATA[The D Programming Language has an impressive list of cool features. That is not always a good thing. A feature should contribute to the philosophy and foundation on which the language was built. If it doesn’t, harmony breaks down and the result is a language that is harder to learn and to use. Some people [...]]]></description>
			<content:encoded><![CDATA[<p>The D Programming Language has an impressive list of cool features. That is not always a good thing. A feature should contribute to the philosophy and foundation on which the language was built. If it doesn’t, harmony breaks down and the result is a language that is harder to learn and to use.</p>
<p>Some people think D suffers from such a feature creep. To some degree I can agree. D has <a href="http://www.hans-eric.com/2007/08/27/contract-programming-in-d/" title="Contract Programming in D">features that are unlikely to become widespread</a>, but most of them are aligned towards a common goal. That goal is bringing productivity to the world of low-level programming.</p>
<p>Lately, a new goal has emerged from the D community, and it has triggered some real intense activity. The future of D seems to lie in the field of functional programming, making the imperative and the functional paradigms truly come together.</p>
<p>Why is this important? Let me quote Walter Bright from <a href="http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&amp;article_id=68443" title="Walter Bright on const">a discussion at the D forums</a>:</p>
<blockquote><p>The future of programming will be multicore, multithreaded. Languages that<br />
make it easy to program them will supplant languages that don&#8217;t.<br />
[…]<br />
The surge in<br />
use of Haskell and Erlang is evidence of this coming trend (the killer<br />
feature of those languages is they make it easy to do multiprogramming).</p></blockquote>
<p>As we all know, multithread programming in an imperative language is a real pain. It’s complicated and easy to get wrong, but that is not the case in a functional language. A pure functional program is thread-safe by design, since it’s free from mutable state and side-effects.</p>
<blockquote><p>You never have to worry about deadlocks and race conditions because you don&#8217;t need to use locks! No piece of data in a functional program is modified twice by the same thread, let alone by two different threads. That means you can easily add threads without ever giving conventional problems that plague concurrency applications a second thought!</p></blockquote>
<p>Quote from Slava Akhmechet’s excellent article <a href="http://www.defmacro.org/ramblings/fp.html">Functional Programming For the Rest of Us</a>.</p>
<p>What the people behind D want to do is to create a true functional subset of the D Programming Language, and create a safe interfacing to parts of the program that are imperative. The functional subset would enforce pure functional programming, like disallowing access to mutable global state and calls to non-pure functions. In effect that would enable you to write parts of your program that need to be thread-safe in a functional style, while using the style of programming that most of us are used to for the rest.</p>
<p>But, it might not stop there. Andrei Alexandrescu, who’s one of the driving forces behind the functional subset, has suggested that the enforcements inside a pure function can be relaxed to allow mutability of what he calls “automatic state,” thus allowing imperative techniques to be used as long as the mutability doesn’t leak across the function barrier. Here’s an example from <a href="http://www.digitalmars.com/d/2.0/accu-functional.pdf" title="Grafting Functional Support on Top of an Imperative Language">Andrei’s slides on the subject</a>:</p>
<pre class="brush: d; title: ; notranslate">
int fun(invariant(Node) n) pure {
  int i = 42;
  if (n.value) ++i;
  int accum = 0;
  for (i = 0; i != n.value; ++i) ++accum;
  return n.value + i;
}
</pre>
<p>This code doesn’t look a bit functional, but the result of fun() is solely dependent on its arguments, so seen from the outside it’s pure.</p>
<p>Mixing pure functional and main stream imperative programming is certainly bleeding-edge. As far as I know it has never been done in any other language. But even though I’m excited, I can’t help wondering whether this is the right way to go. There’s a risk that D spreads itself too thin, and that the pure functional subset of D will be too noisy; I anticipate a heavy use of the invariant keyword for instance.</p>
<p>Would it be a better option to create a completely new language, say Functional D, and make D and Functional D interoperable on a binary level? At least that would battle the noise by reducing the need for explicitly expressing things like immutability, which can be taken for granted in a functional language. I also suspect that the compilers would be less difficult to implement than a compiler that has to support both styles.</p>
<p>But then again, I don’t know much about making compilers. I just happen to be more of a minimalist when it comes to computer languages. (As opposed to my preferences for APIs and Framworks.)</p>
<p>Expect more posts on this subject as I plan to delve into details next.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2008/04/16/the-future-of-d-is-functional/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Steve Yegge: D is the Next Cool Language</title>
		<link>http://www.hans-eric.com/2008/04/01/steve-yegge-d-is-the-next-cool-language/</link>
		<comments>http://www.hans-eric.com/2008/04/01/steve-yegge-d-is-the-next-cool-language/#comments</comments>
		<pubDate>Tue, 01 Apr 2008 17:36:19 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[D Programming Language]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/2008/04/01/steve-yegge-d-is-the-next-cool-language/</guid>
		<description><![CDATA[I just watched an interview with Steve Yegge on the Google Code Blog. The interview was mostly about his current project Rhino on Rails. It was interesting, although not interesting enough to keep my attention for the entire 25 minutes. After some time I kind of tuned out, but I kept the video cast running [...]]]></description>
			<content:encoded><![CDATA[<p>I just watched <a href="http://google-code-updates.blogspot.com/2008/01/interview-with-steve-yegge-on-rhino-on.html" title="Interview with Steve Yegge on Rhino on Rails">an interview with Steve Yegge</a> on the Google Code Blog. The interview was mostly about his current project Rhino on Rails. It was interesting, although not interesting enough to keep my attention for the entire 25 minutes. After some time I kind of tuned out, but I kept the video cast running in the background.</p>
<p>Good thing I did, because at the end of the interview Steve surprised me big time. If you&#8217;ve followed my blog lately you know that the <a href="http://www.hans-eric.com/2007/08/21/agile-low-level-programming-with-d/" title="Agile Low Level Programming With D">D Programming Language is my favorite toy</a> at the moment, so when he mentioned it in the interview I was all ears again. For your convenience, I made a transcript of the best parts:</p>
<blockquote><p><strong>You&#8217;re a language geek. What new cool language would you want to play with next?</strong></p>
<p>To be honest I really wish I knew more about D. I&#8217;ve programmed in the D language and it&#8217;s D-lightful. It was quite expressive. I did a bunch of programs that I kind of ported from ruby scripts that I&#8217;ve written, and I swear it was only like 20% harder than in the ruby code. It was super tight, except that it was lightning fast. It was like C++ or faster.</p></blockquote>
<p>Steve also gives his opinion on what&#8217;s needed for D to become really big.</p>
<blockquote><p>If it [the D language] were link compatible with C++, which is hard, then it could be used with all the C++ libraries. Then it could be the replacement of C++.</p></blockquote>
<p>In case you&#8217;d like to hear and see for yourself, the part when he mentions D starts at about 22 minutes and 35 seconds in.</p>
<p>Steve Yegge as part of the D community? Wouldn&#8217;t that be something.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2008/04/01/steve-yegge-d-is-the-next-cool-language/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>D Update Mitigates Comparison Gotcha</title>
		<link>http://www.hans-eric.com/2008/03/11/d-update-mitigates-comparison-gotcha/</link>
		<comments>http://www.hans-eric.com/2008/03/11/d-update-mitigates-comparison-gotcha/#comments</comments>
		<pubDate>Tue, 11 Mar 2008 18:12:25 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[D Programming Language]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/2008/03/11/d-update-mitigates-comparison-gotcha/</guid>
		<description><![CDATA[The D programming language tries to make a clear distinction between comparison by equality and comparison by identity. It does so by offering two different operators, one for each purpose. As I&#8217;ve written about in a previous post this could be a source of confusion for D newbies, like myself. Someone who&#8217;s used to the [...]]]></description>
			<content:encoded><![CDATA[<p>The D programming language tries to make a clear distinction between comparison by equality and comparison by identity. It does so by offering two different operators, one for each purpose.</p>
<pre class="brush: d; title: ; notranslate">
// Are a and b equal?
if (a == b) { ... }

// Are a and b the same object?
if (a is b) { ... }
</pre>
<p>As I&#8217;ve written about in <a title="D gotchas" href="http://www.hans-eric.com/2007/11/06/d-gotchas/">a previous post</a> this could be a source of confusion for D newbies, like myself. Someone who&#8217;s used to the comparison semantics of Java, for instance, is likely to learn to separate equality and identity the hard way. Until now, that is.</p>
<p>This code, where the equality operator is (wrongly) used to compare identities, used to produce a nasty Access violation error at runtime.</p>
<pre class="brush: d; title: ; notranslate">
SomeObject a = null;
if (a == null) { ... } //&lt;-- Access Violation
</pre>
<p>Now, with the newly released versions of the D compiler (the stable <a title="DMD 1.028 Change Log" href="http://www.digitalmars.com/d/1.0/changelog.html#new1_028">1.028</a> and the experimental <a title="DMD 2.012 Change Log" href="http://ftp.digitalmars.com/dmd.2.012.zip">2.012</a>,) this error is nicely caught by the compiler, which kindly instructs us to use the identity operator instead.</p>
<p><code>Error: use 'is' instead of '==' when comparing with null</code></p>
<p>Unfortunately, it won&#8217;t help us discover all cases of wrongly used equality operators. For instance, this piece of code still produces the dreadful runtime AV.</p>
<pre class="brush: d; title: ; notranslate">
SomeObject a = null;
if (a == a) { ... } // &lt;-- Access Violation
</pre>
<p>Still, the update is a big improvement and will make it easier for a lot of people while learning the language.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2008/03/11/d-update-mitigates-comparison-gotcha/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Open-Closure-Close Idiom in D</title>
		<link>http://www.hans-eric.com/2008/02/13/the-open-closure-close-idiom-in-d/</link>
		<comments>http://www.hans-eric.com/2008/02/13/the-open-closure-close-idiom-in-d/#comments</comments>
		<pubDate>Wed, 13 Feb 2008 13:22:26 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[D Programming Language]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/2008/02/13/the-open-closure-close-idiom-in-d/</guid>
		<description><![CDATA[In a Reddit discussion following my last post on object lifetime management in D, bonzinip wondered why the D closures aren&#8217;t used with the open-closure-close idiom that is common, for instance, in Ruby. bonzinip: languages with closures (Ruby, Smalltalk) use them to ensure that the file is closed when you get out of scope, and [...]]]></description>
			<content:encoded><![CDATA[<p>In a <a href="http://reddit.com/r/programming/info/67z6n/comments">Reddit discussion</a> following <a href="http://www.hans-eric.com/2008/02/07/managing-object-lifetimes-in-d/" title="Managing Object Lifetimes in D">my last post on object lifetime management in D</a>, <em>bonzinip</em> wondered why the D closures aren&#8217;t used with the open-closure-close idiom that is common, for instance, in Ruby.</p>
<blockquote><p>bonzinip: languages with closures (Ruby, Smalltalk) use them to ensure that the file is closed when you get out of scope, and that does <em>not</em> require new keywords and does <em>not</em> require to bypass GC and possibly get dangling pointers.</p>
<p>NovaProspekt: D actually has full closures</p>
<p>bonzinip: so why don&#8217;t they use them with a &#8220;try { open; run closure; } finally { close; }&#8221; idiom instead?</p></blockquote>
<p>Well, let&#8217;s take a look at how that could be accomplished in D.</p>
<p>To get an image of the open-closure-close idiom, we can look at Ruby&#8217;s File class, and particularly <a href="http://www.ruby-doc.org/core/classes/IO.html#M002264" title="IO::open">the open method</a>.</p>
<blockquote><p>IO.open(fd, mode_string=&#8221;r&#8221; )               =&gt; io<br />
IO.open(fd, mode_string=&#8221;r&#8221; ) {|io| block } =&gt; obj</p>
<p>With no associated block, open is a synonym for IO::new. If the optional code block is given, it will be passed <em>io</em> as an argument, and the IO object will automatically be closed when the block terminates. In this instance, <tt>IO::open</tt> returns the value of the block.</p></blockquote>
<p>What this means is that a File can be opened, either in the normal way with explicit closing (begin-ensure corresponds to try-finally in D)</p>
<pre><code>f = File.open("c:\\log.txt", "w")
begin
  f.puts "Log this"
ensure
  f.close
end
</code></pre>
<p>or with a code block (closure)</p>
<pre><code>File.open("c:\\log.txt", "w") do |f|
  f.puts "Log this"
end</code></pre>
<p>In this last example the file is both opened and closed by the open method, in between the method invokes the associated code block with the file object reference as a parameter (f). In essence, that is the open-closure-close idiom.</p>
<p>How could we do this in D? Well, <a href="http://www.hans-eric.com/2008/01/17/loop-abstractions-in-d/" title="Loop Abstractions in D">as I&#8217;ve written before</a>, D&#8217;s delegates in combination with function literals can be used to mimic the code blocks of Ruby.  So, a D version of the File::open method could look something like this:</p>
<pre><code>import std.stdio;
import std.stream;

void open_run_close(char[] fn, FileMode fm = FileMode.In,
  void delegate(Stream) closure)
{
  Stream f = new File(fn, fm);
  try {
    closure(f);
  } finally {
    f.close();
  }
}</code></pre>
<p>and be invoked like this:</p>
<pre><code>open_run_close("c:\\log.txt", FileMode.Out, (Stream f) {
  OutputStream os = f;
  os.writefln("Log this");
});</code></pre>
<p>To make it a little more like the original Ruby version, let&#8217;s make it support the non-closure variant as well.</p>
<pre><code>Stream open_run_close(char[] fn, FileMode fm = FileMode.In,
void delegate(Stream) closure = null)
{
  Stream f = new File(fn, fm);
<strong>  if (!closure) {
    return f;
  } else {
</strong>    try {
      closure(f);
<strong>      return null;</strong>
    } finally {
      f.close();
    }
<strong>  }</strong>
}

// Example usage
open("c:\\log.txt", FileMode.Out, (Stream f) {
  OutputStream os = f;
  os.writefln("Log this");
});

// Example traditional usage
OutputStream f = open("c:\\log2.txt", FileMode.Out);
try {
  f.writefln("Do log this");
} finally {
  f.close;
}</code></pre>
<p>The open-closure-close idiom is definitely doable in D. It&#8217;s not as pretty and natural as in Ruby, but not so far from it either. Whether this particular idiom will be embraced by the D community is yet to be seen.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2008/02/13/the-open-closure-close-idiom-in-d/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Managing Object Lifetimes in D</title>
		<link>http://www.hans-eric.com/2008/02/07/managing-object-lifetimes-in-d/</link>
		<comments>http://www.hans-eric.com/2008/02/07/managing-object-lifetimes-in-d/#comments</comments>
		<pubDate>Thu, 07 Feb 2008 13:53:33 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[D Programming Language]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/2008/02/07/managing-object-lifetimes-in-d/</guid>
		<description><![CDATA[The D Programming Language is a modern version of C. It adds productivity features to the performance power of C, features like object oriented programming and garbage collection. It may seem strange that a language with focus on performance utilizes automatic memory management. A GC equals overhead, right? Well, actually that is a common misconception. [...]]]></description>
			<content:encoded><![CDATA[<p>The D Programming Language is a modern version of C. It adds productivity features to the performance power of C, features like object oriented programming and garbage collection.</p>
<p>It may seem strange that a language with focus on performance utilizes automatic memory management. A <abbr title="Garbage Collector">GC</abbr> equals overhead, right? Well, actually <a href="http://www.ibm.com/developerworks/java/library/j-jtp09275.html?S_TACT=105AGX02&amp;S_CMP=EDU" title="Urban performance legends, revisited">that is a common misconception</a>. These days implicitly memory managed code is generally faster than code where the programmer handles deallocations. One reason for this counter-intuitive fact is that a number of optimizations can be done by the GC, especially on short-lived objects.</p>
<p>But garbage collection isn’t a problem free feature. For one thing, it is indeterministic. Normally, an object that uses external resources acquires them in a constructor and releases them in the destructor.</p>
<pre><code>import std.stream;

class LogFile {
  File f;

  this() {
    f = new File("c:\\log.txt", FileMode.Out);
  }

  ~this() {
    f.close;
  }

  // Logging methods goes here
}</code></pre>
<p>But with a GC there is no way to know when or even if the destructor is run. This may be a problem if you’re dealing with scarce resources like window handles, or file locks. So how can we control object destructions in a GC capable language? One possibility is to trigger a GC sweep explicitly in your code. In D this is done with the fullCollect function.</p>
<pre><code>import std.gc;

fullCollect();</code></pre>
<p>Explicit trigging of garbage collection is usually a bad idea, for several reasons. For one thing, it&#8217;s like killing an ant with a bazooka, and still you risk missing the target. Therefore, the normal approach to deal with the problem of indeterminism is to use a dispose method.</p>
<pre><code>class LogFile {
  File f;

  this() {
    f = new File("c:\\log.txt", FileMode.Out);
  }

  ~this() {
    <strong>dispose();</strong>
  }

<strong>  void dispose() {
    if (f !is null) {
      f.close;
      f = null;
    }
  }
</strong>
  // Logging methods here
}

LogFile log = new LogFile();
try {
  // Do some logging
} finally {
  <strong>log.dispose;</strong>
}</code></pre>
<p>We don’t have to use the dispose pattern though because in D we have the luxury of choosing between implicit and explicit memory management. We can either free the object ourselves with the delete operator, or leave it for the GC to dispose later.</p>
<pre><code>LogFile log = new LogFile();
try {
  // Do some logging
} finally {
  delete log; // Explicit memory management
}</code></pre>
<p>D has another construct which is very convenient when you need to control the lifetime of an object. With the scope attribute, an object is automatically destroyed when the program leaves the scope in which the object was created.</p>
<pre><code>void function some_func() {
<strong>  scope </strong>LogFile log = new LogFile();
  :
  // log will be freed on exit
}</code></pre>
<p>The ability to mix explicit and implicit memory management is a simple, yet great feature. It is one of many examples where D provides us with the best of two worlds. Convenience and control, as well as productivity and performance, is blended in a way that has no equivalence in any other language I know.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2008/02/07/managing-object-lifetimes-in-d/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Loop Abstractions in D revisited</title>
		<link>http://www.hans-eric.com/2008/01/31/loop-abstractions-in-d-revisited/</link>
		<comments>http://www.hans-eric.com/2008/01/31/loop-abstractions-in-d-revisited/#comments</comments>
		<pubDate>Thu, 31 Jan 2008 15:31:22 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[D Programming Language]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/2008/01/31/loop-abstractions-in-d-revisited/</guid>
		<description><![CDATA[In my previous post on Loop Abstractions in D I showed you how we could make loop constructs abstract, in a similar way which is common in Ruby. The example I used as a model was the retryable method from Cheah Chu Yeow. His version is customizable in a way that let you define the [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.hans-eric.com/2008/01/17/loop-abstractions-in-d/">my previous post on Loop Abstractions in D</a> I showed you how we could make loop constructs abstract, in a similar way which is common in Ruby. <a href="http://blog.codefront.net/2008/01/14/retrying-code-blocks-in-ruby-on-exceptions-whatever/">The example I used as a model</a> was the retryable method from Cheah Chu Yeow. His version is customizable in a way that let you define the type of exception that triggers a retry.</p>
<pre><code>retryable(:tries =&gt; 5, <strong> <img src='http://www.hans-eric.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> n =&gt; OpenURI::HTTPError</strong>) do
  # retryable code goes here
end</code></pre>
<p>To mimic that in D we had to use templates, which are invoked with a special syntax.</p>
<pre><code>retryable<strong>!(HTTPError)</strong>({
  // Retryable code goes here
}, 5);</code></pre>
<p>To be honest, I don&#8217;t like the template syntax. I don&#8217;t know why, it just doesn&#8217;t feel right. If possible, I&#8217;d much prefer a more native looking code. Maybe something like this:</p>
<pre><code>retryable({
  // Retryable code goes here
}<strong>, 5, HTTPError</strong>);</code></pre>
<p><a href="http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D.learn&amp;article_id=10821">Christopher Wright points out an implementation</a> that would be the closest one could get to a signature like that. He uses the somewhat primitive <abbr title="RunTime Type Information">RTTI</abbr> in D.</p>
<pre><code>void retryable(<strong>ClassInfo info</strong>, int times,
  void delegate() totry)
{
  for (int i = 0; i &lt; times; i++) {
    try {
      totry();
      break;
    } catch (Exception e) {
      <strong>if (e.classinfo is info) continue; else throw e;</strong>
    }
  }
}</code></pre>
<p>Which could be invoked with the following code.</p>
<pre><code>retryable(HTTPError.classinfo, 5, {
  // Retryable code goes here
});</code></pre>
<p>The problem with this approach, which was <a href="http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D.learn&amp;article_id=10823">pointed out by Jarret Billingsley</a>, is that this implementation wouldn&#8217;t catch and retry on exceptions from derived classes (descendants to HTTPError in the above example). Fortunately, Jarret provides us with a solution.</p>
<blockquote><p> What you have to do then is perform a dynamic cast.  There&#8217;s no syntax for this, but you can<br />
hack around with some of the runtime functions to do the same thing.  Place:</p>
<pre><code>extern(C) Object _d_dynamic_cast(Object o, ClassInfo c);</code></pre>
<p>somewhere in your module, then in the catch clause of retryable:</p>
<pre><code>catch(Exception e)
{
  if(_d_dynamic_cast(e, info))
    continue;
  else
    throw e;
}</code></pre>
<p>That _should_ work.  It&#8217;s doing the same thing as the cast operator would<br />
but without the pretty syntax.</p></blockquote>
<p>Not pretty, but it works, at least if you use one of the standard libraries: <a href="http://www.dsource.org/projects/tango/">Tango</a> or <a href="http://www.digitalmars.com/d/2.0/phobos/phobos.html">Phobos</a>. I&#8217;m not sure it&#8217;s better than the template version though. The .classinfo property brings nearly as much noice as the template version does. Also, the template version has the advantage that it is resolved at compile-time.</p>
<p>I think I&#8217;ll go with templates after all. Who knows, I might even get used to them one day.</p>
<p>Cheers! <img src='http://www.hans-eric.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2008/01/31/loop-abstractions-in-d-revisited/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Loop Abstractions in D</title>
		<link>http://www.hans-eric.com/2008/01/17/loop-abstractions-in-d/</link>
		<comments>http://www.hans-eric.com/2008/01/17/loop-abstractions-in-d/#comments</comments>
		<pubDate>Thu, 17 Jan 2008 21:32:29 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[D Programming Language]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/2008/01/17/loop-abstractions-in-d/</guid>
		<description><![CDATA[One of the great things with Ruby is the natural way in which you can hide looping constructs behind descriptive names. Like the retryable example that Cheah Chu Yeow gives on his blog. retryable(:tries =&#62; 5, n =&#62; OpenURI::HTTPError) do open('http://example.com/flaky_api') end Notice how elegantly the loop logic is abstracted; There&#8217;s no need to look [...]]]></description>
			<content:encoded><![CDATA[<p>One of the great things with Ruby is the natural way in which you can hide looping constructs behind descriptive names. Like <a href="http://blog.codefront.net/2008/01/14/retrying-code-blocks-in-ruby-on-exceptions-whatever/" title="Retrying code blocks in Ruby">the retryable example</a> that Cheah Chu Yeow gives on his blog.</p>
<blockquote>
<pre>retryable(:tries =&gt; 5, <img src='http://www.hans-eric.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> n =&gt; OpenURI::HTTPError) do
  open('http://example.com/flaky_api')
end</pre>
</blockquote>
<p>Notice how elegantly the loop logic is abstracted; There&#8217;s no need to look at the implementation of retryable to figure out what it does. The question is, can we do something similar with D as well? It turns out that with features like <a href="http://www.digitalmars.com/d/type.html#delegates">delegates</a> and <a href="http://www.digitalmars.com/d/type.html#FunctionLiteral">function literals</a> we can actually get pretty close.</p>
<pre><code>bool retryable(int tries, void delegate() dg)
{
  for(int i = tries; i &gt; 0; i&#45;&#45;)
  {
    try
    {
      dg();
      return true;
    }
    catch
    {
      // Retry
    }
  }
  return false;
}</code></pre>
<p>Which can be used like this:</p>
<pre><code>retryable(5, {
  open("http://example.com/flaky_api");
}) ;</code></pre>
<p>Not as nice as with Ruby, but almost.</p>
<p>The custom exception of the Ruby version is a tricky one to implement in D. Templates to our rescue.</p>
<pre><code>bool retryable<strong>(E)</strong>(int tries, void delegate() dg)
{
  for(int i = tries; i &gt; 0; i&#45;&#45;)
  {
    try
    {
      dg();
      return true;
    }
    catch <strong>(E)</strong>
    {
      // Retry
    }
  }
  return false;
}</code></pre>
<p>With the (little bit odd) template syntax, we can then make retryable retry only when, for example, StdioExceptions are thrown.</p>
<pre><code>retryable!(StdioException)(5, {
  open("http://example.com/flaky_api");
}) ;</code></pre>
<p>To clean it up a bit, we can add some defaults (which requires us to switch places between the parameters).</p>
<pre><code>bool retryable(E <strong>= Exception</strong>)(<strong>void delegate() dg, int tries = 5</strong>)
{
  for(int i = tries; i &gt; 0; i&#45;&#45;)
  {
    try
    {
      dg();
      return true;
    }
    catch (E)
    {
      // Retry
    }
  }
  return false;
}</code></pre>
<p>That gives us a little more freedom when utilizing retryable.</p>
<pre><code>retryable({
  // Retry up to 5 times
});

retryable({
  // Retry up to 10 times
}, 10);

retryable!(StdioException)({
  // Retry up to three times
  // on StdioException failures
}, 3);</code></pre>
<p>I totally agree with Cheah Chu that Ruby is nice, but I think D is pretty cool too.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2008/01/17/loop-abstractions-in-d/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>D Gotchas</title>
		<link>http://www.hans-eric.com/2007/11/06/d-gotchas/</link>
		<comments>http://www.hans-eric.com/2007/11/06/d-gotchas/#comments</comments>
		<pubDate>Tue, 06 Nov 2007 16:06:18 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[D Programming Language]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/2007/11/06/d-gotchas/</guid>
		<description><![CDATA[I have been playing around with the D Programming Language lately, and I love it. D combines the low-level control of C and modern productivity features like garbage collection, a built in unit-testing framework and &#8211; the most recent feature &#8211; real closures. But D is still a young language, and as such a little [...]]]></description>
			<content:encoded><![CDATA[<p>I have been playing around with the <a href="http://www.digitalmars.com/d">D Programming Language</a> lately, and I love it. D combines the low-level control of C and modern productivity features like garbage collection, <a href="http://www.hans-eric.com/2007/08/21/agile-low-level-programming-with-d/" title="Agile Low-level Programming in D">a built in unit-testing framework</a> and &#8211; the most recent feature &#8211; <a href="http://www.hans-eric.com/2007/11/03/d-got-real-closures/" title="D Got Real Closures">real closures</a>.</p>
<p>But D is still a young language, and as such a little rough around the edges. It jumps out and bites me every now and then, forcing me to change some of my most common coding habits. Here are a couple of gotchas that made me trip more than once.</p>
<p><strong>Premature Convertion</strong></p>
<p>What&#8217;s the value of the variable after the assignment below?</p>
<pre>real a = 5/2;</pre>
<p>In D, the answer is 2. The reason for this unintuitive behavior is <a href="http://www.digitalmars.com/d/type.html">D&#8217;s arithmetic conversion rules</a> which only takes operand types into consideration. A division between two integers result in an integer as well. The desired type, the type of the resulting variable, is disregarded.</p>
<p>To get the desired result we need to convert at least one of the operands to a floating-point number. This can be done in two ways. Either literally:</p>
<pre>real a = 5.0/2; // a=&gt;2.5</pre>
<p>Or with an explicit cast:</p>
<pre>real a = cast(real)5/2; // a=&gt;2.5</pre>
<p>Note that you must convert the operand, not the result. So this won&#8217;t work:</p>
<pre>real a = cast(real)(5/2); // a=&gt;2</pre>
<p>The Premature Conversion gotcha is a particularly nasty one. It compiles and runs, which means only testing can reveal this bug.</p>
<p><strong>Testing for identity</strong></p>
<p>I&#8217;m a defensive programmer. I like to put assertions whenever I make assumptions in my code. By far, the most common assumption I make, is that an object is assigned. Here&#8217;s how I normally do it:</p>
<pre>assert(o != null, "o should be assigned!");</pre>
<p>In D, this is a big gotcha. The code above works as long as o is not null. If o is unassigned, we&#8217;ll get a nasty Access Violation Error. Here&#8217;s another example:</p>
<pre>SomeObject o = null;
if (o == null) // &lt;= Access Violation
  o = new SomeObject;</pre>
<p>The reason is that D supports overloaded operators, in this case the equality operators (== and !=). Unlike Java, D converts the equality operator into a method call without checking for null references. So, internally, the above code gets converted to the following:</p>
<pre>SomeObject o = null;
if (o.opEquals(null))
  o = new SomeObject;</pre>
<p>Since o is null, the call to opEquals result in an Access Violation. Instead you should use the <em>is operator</em> to check for identity.</p>
<pre>if(o is null) ...</pre>
<p>Or</p>
<pre>assert(o !is null, ...)</pre>
<p>Despite the tripping, I actually like the idea of a separate identity operator. After all, &#8220;is a equivalent to b?&#8221; is a different question than &#8220;are a and b the same object?&#8221;. But, as we say in Sweden, It&#8217;s difficult to teach old dogs to sit.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2007/11/06/d-gotchas/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
	</channel>
</rss>

