<?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>twistedoakstudios.com</title>
	<atom:link href="http://twistedoakstudios.com/blog/feed" rel="self" type="application/rss+xml" />
	<link>http://twistedoakstudios.com/blog</link>
	<description></description>
	<lastBuildDate>Tue, 18 Jun 2013 06:18:08 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Unfathomable Bugs #6: Pretend Precision</title>
		<link>http://twistedoakstudios.com/blog/Post4428_unfathomable-bugs-6-pretend-precision</link>
		<comments>http://twistedoakstudios.com/blog/Post4428_unfathomable-bugs-6-pretend-precision#comments</comments>
		<pubDate>Tue, 18 Jun 2013 06:17:28 +0000</pubDate>
		<dc:creator>Craig Gidney</dc:creator>
				<category><![CDATA[Bugs]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Unfathomabls Bugs]]></category>

		<guid isPermaLink="false">http://twistedoakstudios.com/blog/?p=4428</guid>
		<description><![CDATA[Today’s bug comes courtesy of Apple. Thank you, Apple, this series wouldn’t exist without the generous support of entities like you. &#8212; It&#8217;s Friday evening. Me and my coworker Jazz are sitting at my desk. Our secure telephony client written in Objective-C is failing to initiating calls and we don&#8217;t know why. We catch some [...]]]></description>
				<content:encoded><![CDATA[<p>Today’s bug comes courtesy of Apple. Thank you, Apple, this series wouldn’t exist without the generous support of entities like you.</p>
<p>&#8212;</p>
<p>It&#8217;s Friday evening. Me and my coworker Jazz are sitting at my desk. Our secure telephony client written in Objective-C is failing to initiating calls and we don&#8217;t know why. We catch some minor things, until Jazz notices a specific reproducible problem: the client is sending a <a href="http://en.wikipedia.org/wiki/Json">JSON</a>-encoded session id that&#8217;s slightly off. It&#8217;s almost correct, except for the last few digits.</p>
<p>I figure the bug has to be in the JSON serialization code. It doesn&#8217;t matter that I&#8217;ve previously stepped over the serialization code <em>line by line</em> in the debugger, and confirmed its correctness by checking the raw values against the corresponding JSON. It doesn&#8217;t matter that we&#8217;re not actually doing anything fancy, just calling the built-in JSON methods. There&#8217;s simply <em>nothing else</em> that touches the session id: we never generate ids client side, and we never do arithmetic on them.</p>
<p>I must be missing something stupid.</p>
<h3>Serial Confusion</h3>
<p>I decide to start from the simplest possible parsing code that works, using only actual data received from the server, and then <em>slowly</em> add details until the bug appears. This is a good approach to take when a bug renews your fear that computer gnomes might really exist.</p>
<p>I make a tiny test that simply has to work:</p>
<pre><code class="prettyprint">NSString* json = @"{\"sessionId\":6032314514195021674}";
    
NSData* jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError* err;
NSDictionary* obj = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&#038;err];
    
NSNumber* sessionId = [obj objectForKey:@"sessionId"];
test([sessionId isEqualToNumber:@6032314514195021674]);
<strong><span style="background-color: #008000;">PASS</span></strong></code></pre>
<p>See? It works. The parsed session id equals the correct value. Good. It would have been really inconvenient if that test failed.</p>
<p>I need to add a tiny detail now. We actually store the int64_t value of the NSNumber instead of the NSNumber itself. That value is accessed by using &#8216;longLongValue&#8217;.</p>
<p>I test that longLongValue also returns the right value:</p>
<pre><code class="prettyprint">...

test([sessionId isEqualToNumber:@6032314514195021674]);
<strong><span style="background-color: #008000;">PASS</span></strong>
test([sessionId longLongValue] == 6032314514195021674);
<strong><span style="background-color: #800000;">FAIL: 6032314514195021824 != 6032314514195021674</span></strong></code></code></pre>
<p>Wait&#8230; what? The wrong long long came out.</p>
<p>Long longs are guaranteed to have at least 64 bits, and this particular session id should fit into a 64 bit integer, so there should be no rounding or other tom-foolery. Maybe there&#8217;s some issue with the longLongValue method, or storing such large values in an NSNumber?</p>
<p>I test if an NSNumber literal has the same issue:</p>
<pre><code class="prettyprint">...

test([sessionId isEqualToNumber:@6032314514195021674]);
<strong><span style="background-color: #008000;">PASS</span></strong>
test([sessionId longLongValue] == 6032314514195021674);
<strong><span style="background-color: #800000;">FAIL: 6032314514195021824 != 6032314514195021674</span></strong>
test([@6032314514195021674 longLongValue] == 6032314514195021674);
<strong><span style="background-color: #008000;">PASS</span></strong></code></pre>
<p>WHAT? The long long I pulled out of the parsed NSNumber is not equal to the value I pulled out of an <em>equal</em> literal NSNumber.</p>
<p>I&#8217;m really confused. Equal things are supposed to give equal results when run through a function. That&#8217;s like&#8230; a fundamental part of being equal.</p>
<p>Maybe I&#8217;m supposed to be accessing this value in a different way? I start trying things. Using unsignedLongLongValue&#8230; same problem. Using decimalValue&#8230; error? Weird. Using description&#8230;:</p>
<pre><code class="prettyprint">...

test([sessionId isEqualToNumber:@6032314514195021674]);
<strong><span style="background-color: #008000;">PASS</span></strong>
test([sessionId longLongValue] == 6032314514195021674);
<strong><span style="background-color: #800000;">FAIL: 6032314514195021824 != 6032314514195021674</span></strong>
test([@6032314514195021674 longLongValue] == 6032314514195021674);
<strong><span style="background-color: #008000;">PASS</span></strong>
test([[sessionId description] longLongValue] == 6032314514195021674);
<strong><span style="background-color: #008000;">PASS</span></strong></code></pre>
<p>YOU HAVE GOT TO BE KIDDING. The description of the session id has more precision, with respect to the result of longLongValue, than the session id itself!</p>
<p>This is pretty weird, but at least it explains why I thought the code was correct when I stepped through it. When I logged values or looked at them in the debugger, I was seeing their descriptions. I assumed that the descriptions accurately reflected the values. Apparently that was a bad idea. Still&#8230; what&#8217;s going on under the hood, to make all of this happen?</p>
<h3>Seeing Double</h3>
<p>If I was coding in Javascript (the language JSON is derived from), the reason for the last few digits changing would be obvious: <a href="http://stackoverflow.com/a/5353473/52239">all numbers are doubles</a> in JavaScript. Doubles can&#8217;t represent all 64 bit integers. My test session id (6032314514195021<strong>674</strong>) is one of those unrepresentable-as-double integers. Casting it to a double and back rounds it to, you guessed it, the extracted long long value (6032314514195021<strong>824</strong>).</p>
<p>Of course, I&#8217;m coding in Objective-C, not JavaScript. I am parsing data in JavaScript Object Notation, but the <a href="http://www.ietf.org/rfc/rfc4627.txt?number=4627">RFC that describes the JSON format</a> makes no mention of interpreting numbers as doubles. The closest thing I found is in Section 4: &#8220;An implementation may set limits on the range of numbers.&#8221;. Whoever implemented the JSON parsing in Objective-C must have chosen to save time by parsing all numbers as if they were doubles, even if a particular value couldn&#8217;t be represented as a double but could be represented by another common numeric type in Objective-C.</p>
<p>The decision to treat all numbers as doubles is questionable, and inconvenient for me since the python and Java code I&#8217;m supposed to be interacting with both handle 64-bit numbers in JSON just fine, but it&#8217;s not wrong.</p>
<p>What <em>is</em> wrong is saying the two NSNumbers are equal when they don&#8217;t contain the same value.</p>
<h3>Questionable Equality</h3>
<p>Remember from earlier, that the parsed session id was considered equal to an NSNumber literal that ended up having a different longLongValue. My best guess as to why this happens is that a comparison between an NSNumber containing a long long and an NSNumber containing a double just secretly throws away precision on the long long before doing the comparison, by casting to double. I decided to test this, to be sure:</p>
<pre><code class="prettyprint">
NSNumber* d = @6032314514195021674.0; // double
NSNumber* n = @6032314514195021674; // long long

test([d isEqualToNumber:n]);
<strong><span style="background-color: #008000;">PASS</span></strong>
test([d longLongValue] == [n longLongValue]);
<strong><span style="background-color: #800000;">FAIL: 6032314514195021824 != 6032314514195021674</span></strong>
test([[d description] isEqualToString:[n description]]);
<strong><span style="background-color: #800000;">FAIL: "6.032314514195022e+18" != "6032314514195021674"</span></strong>
</code></pre>
<p>Ugh.</p>
<p>Throwing away precision before checking for equality is a <em>highly</em> questionable decision on Apple&#8217;s part. It&#8217;s as if <code>0.3 == 0</code> evaluated to <code>true</code> because <code>(int)0.3 == (int)0</code>. Comparing a float to an integer might be <a href="http://twistedoakstudios.com/blog/Post3044_my-bug-my-bad-2-sunk-by-float">hard to do correctly</a>, but that doesn&#8217;t mean you can just pretend a long long will fit into a double!</p>
<p><em>Side note</em>: In many languages, the expression <code>6032314514195021672 == 6032314514195021674.0</code> will return true, because 64-bit integers are automatically promoted to doubles. I think that implicitly promoting 64-bit integers to doubles is a mistake (because it loses precision), but it&#8217;s worse with NSNumber because the types aren&#8217;t available. A static verifier can detect comparing an int64_t to a double very easily, but if you tried to do the same thing with NSNumbers you&#8217;d be swamped by false positives because it&#8217;s difficult to prove that an NSNumber can&#8217;t be a double or an int64_t.</p>
<p>Moving on from the throwing-away-precision-when-comparing issue, there&#8217;s one interesting difference highlighted by the above test. The NSNumber created from the double literal has a description whose precision matches its value. That contradicts what I saw with the NSNumber parsed from JSON.</p>
<h3>Other Numbers</h3>
<p>It&#8217;s important to understand that objective C has interfaces, instead of classes. Even basic types like NSNumber may have multiple implementations. There might be an NSNumber for doubles, an NSNumber for ints, and maybe lots of other specialized ones. Not that you should have to care, because they all conveniently expose the same interface: NSNumber.</p>
<p>With that in mind, I think the NSNumber returned from the JSON parser is a specialized NSNumber. One modified to keep a copy of the JSON it was parsed from as its description. This would be useful for uses cases like modifying JSON without losing information in the parts you didn&#8217;t touch.</p>
<p>Putting it all together, I have a plausible/questionable reason for each part to work the way it does and I understand how they combined to trick me for so long:</p>
<ul>
<li> Numbers parsed from JSON are all treated as having double-precision; probably because doing that saved on expensive development time.
<li> Numbers parsed from JSON use the text they were parsed from as their description even if that description has extra precision; probably to allow better round-tripping of data.
<li> NSNumbers that contain long longs have their values rounded when being compared to NSNumbers containing doubles; probably because it was easier than doing it correctly, and that&#8217;s what == does in C.
<li> The above three combined mean a number parsed from JSON will acts as if it has full precision, when printed out or compared to the expected value, but it really doesn&#8217;t.
</ul>
<p>Tricky. <em>Complicated</em> tricky.</p>
<h3>Summary</h3>
<p>Objective-C lies about how much precision NSNumbers parsed from JSON have. If you print one out, you see the exact integer value that was parsed. If you compare one to an NSNumber containing the expected value, they&#8217;re equal. If you actually try to access the integer value, it&#8217;s been rounded to the nearest representable double.</p>
<p>You can work around the issue by using the numeric value of the description:</p>
<p><code class="prettyprint">// broken:<br />
int64_t roundedValue = [lyingValueParsedFromJson longLongValue]<br />
// "fixed":<br />
int64_t actualValue = [[lyingValueParsedFromJson description] longLongValue]</code></p>
<p>Make sure you leave a comment explaining that workaround, or maintainers will face-palm for the wrong reason.</p>
<p>&#8212;</p>
<h3>Discuss on <a href="http://www.reddit.com/r/programming/comments/1gkjgo/unfathomable_bug_pretend_precision/">Reddit</a></h3>
<p>&#8212;</p>
]]></content:encoded>
			<wfw:commentRss>http://twistedoakstudios.com/blog/Post4428_unfathomable-bugs-6-pretend-precision/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My Bug, My Bad #3: Accidentally Attacking WarCraft 3</title>
		<link>http://twistedoakstudios.com/blog/Post4281_my-bug-my-bad-3-accidentally-attacking-warcraft-3</link>
		<comments>http://twistedoakstudios.com/blog/Post4281_my-bug-my-bad-3-accidentally-attacking-warcraft-3#comments</comments>
		<pubDate>Tue, 11 Jun 2013 06:17:26 +0000</pubDate>
		<dc:creator>Craig Gidney</dc:creator>
				<category><![CDATA[Bugs]]></category>
		<category><![CDATA[Warcraft3]]></category>

		<guid isPermaLink="false">http://twistedoakstudios.com/blog/?p=4281</guid>
		<description><![CDATA[In web programming, a classic mistake is assuming that you can validate data by asking the web browser to do it. That&#8217;s roughly what went wrong between Tinker and WarCraft 3. Tinkering Years ago, I was working on a hobby project I later called Tinker. Tinker was a game hosting bot for WarCraft 3. Hostbots [...]]]></description>
				<content:encoded><![CDATA[<p>In web programming, a classic mistake is assuming that you can validate data by <a href="http://stackoverflow.com/q/162159/52239">asking the web browser to do it</a>. That&#8217;s roughly what went wrong between Tinker and WarCraft 3.</p>
<h3>Tinkering</h3>
<p>Years ago, I was working on a hobby project I later called <a href="https://github.com/Strilanc/Tinker">Tinker</a>. Tinker was a game hosting bot for <a href="http://en.wikipedia.org/wiki/Warcraft_3">WarCraft 3</a>.</p>
<p>Hostbots are useful for a variety of reasons I won&#8217;t go into, but mostly I enjoyed Tinker as a technical challenge: a way to experiment with small amounts of reverse engineering, to explore programming techniques (e.g. <a href="http://en.wikipedia.org/wiki/Actor_model">actor model</a>, <a href="http://en.wikipedia.org/wiki/Strategy_pattern">strategy pattern</a>, <a href="http://en.wikipedia.org/wiki/Parser_combinator">parser combinators</a>), and to seriously try out some code verification tools (e.g. <a href="http://research.microsoft.com/en-us/projects/contracts/">Code Contracts</a>, <a href="http://msdn.microsoft.com/en-us/library/3z0aeatx.aspx">Code Analysis</a>, <a href="http://research.microsoft.com/en-us/projects/pex/">Pex</a>, <a href="http://research.microsoft.com/en-us/projects/chess/">CHESS</a>).</p>
<p>I did most of my reverse engineering by analyzing the information exchanged between Battle.net and the WarCraft 3 client. I would start WarCraft 3 and <a href="http://en.wikipedia.org/wiki/Wireshark">Wireshark</a>, perform an action in the game, see what information was sent, figure out the structure of the information, and program the bot to mimic that structure.</p>
<p>Because I was inferring the structure of packets by observation, I&#8217;d often miss small details. I&#8217;d think some value was always 0, but it turned out there was a corner case where it was supposed to be 1, or whatever.</p>
<p>Typically, the consequence for getting a detail wrong was all of the players immediately disconnecting from the bot&#8217;s game, or the bot being immediately disconnected by Battle.net. An annoying but ultimately minor consequence, in the scheme of things. Typically.</p>
<h3>Making a Game and a Bug</h3>
<p>As a player, creating a custom game in WarCraft 3 is relatively simple: you choose a map and a game name then click &#8220;Create Game&#8221;, for the most part.</p>
<p>As a programmer, things aren&#8217;t so simple. You need to know the type of packet used to create a game, where the game name goes in that packet, how the game name is encoded (<a href="http://en.wikipedia.org/wiki/Null-terminated_string">null-terminated</a> <a href="http://en.wikipedia.org/wiki/Utf8">UTF8</a>), how maps are identified (path relative to program folder and a <a href="http://en.wikipedia.org/wiki/Crc32">few</a> <a href="http://www.wc3c.net/showthread.php?p=1035239#post1035239">sometimes-quirky</a> <a href="http://en.wikipedia.org/wiki/Sha1">checksums</a>), where <em>they</em> go in the packet, what game settings there are, how they are encoded (<a href="http://en.wikipedia.org/wiki/Flag_word">bit flags</a>), if there&#8217;s any sort of trickery to avoid zeroes because all these things are being shoved into a null-terminated string (<a href="https://github.com/Strilanc/Tinker/blob/master/Warcraft3/Protocol/GameStatsJar.vb#L192">yes</a>), and etc. Remember: get a detail wrong, and your user gets disconnected instead of making a game.</p>
<p>Obviously, as part of writing a game hosting bot, I had to write code to generate &#8216;create game&#8217; packets (a lot of the work <a href="http://www.bnetdocs.org/?op=packet&#038;pid=265">had already been done</a>). However, in doing so, I missed one important caveat: in Warcraft, the game name text box stops taking input after 31 characters. In fact, game names longer than 31 characters are considered invalid.</p>
<p>Whatever. No big deal, right? Someone will try to make a game with a long name, and their bot will get disconnected. They&#8217;ll contact me, give me the logs, and I&#8217;ll figure out the problem. Typical bug fix. Annoying for the user, but nothing serious.</p>
<h3>No Games for Anyone</h3>
<p>Things weren&#8217;t so typical, this time. I had no idea anything was wrong until I received a private message:</p>
<blockquote><p><strong>Urgent: HostBot<br />
</strong><br />
gamename = &#8220;0123456789012345678901234567890&#8243; // (legal)<br />
gamename2 = &#8220;01234567890123456789012345678901&#8243; // (illegal)</p>
<p>You need to implement a max gamename length to your HostBot program NOW. If a game is hosted on a server with a name that is longer than the max game length imposed by WC3, <strong>everyone who views the Custom Game list on that server gets instant disconnection</strong> [emphasis mine].</p>
<p>It appears the max gamename length is 31 characters.</p>
<p>I love your HostBot program, don&#8217;t get me wrong but&#8230; your software is the only freely available software I know of that can create this problem, and its been happening frequently (once every couple of days on USEast, the custom game list goes down for hours at a time).</p>
<p>Its pretty hard to believe that Blizzard have left such a problem in Bnet, but their software was never setup to deal with the freedom your HostBot currently gives.</p>
<p>Thanks!</p></blockquote>
<p>Oh Sh-&#8230;..oot. Tinker allowed too-long game names, and the Battle.net servers <em>were accepting them</em>! The servers would then broadcast the invalid names to any WarCraft 3 client that asked for the custom games list, causing the client to <em>disconnect from Battle.net</em>. Users of my bot were accidentally performing denial-of-service attacks on the custom games list and <em>taking it down for the entire realm for hours at a time</em>!</p>
<p>Hundreds, maybe thousands, of people were being actively inconvenienced by a mistake I made. I fixed the bug as quickly as possible. I informed Varlock/hogantp, maker of the better-known <a href="http://code.google.com/p/ghostplusplus/">GHost</a>. I informed Blizzard.</p>
<p>I was a bit worried blizzard would just ignore the issue, becauset of my experience with them chronically ignoring suggestions made by the mapping community. However, a few days later, sending a too-long game name would correctly disconnect the bot instead of everyone else. Maybe Blizzard noticed the problem on their own.</p>
<h3>Summary</h3>
<p>Users of Tinker were accidentally preventing everyone from playing custom WarCraft 3 games, because I didn&#8217;t realize (and Blizzard half-forgot) that game names were required to have fewer than 32 characters.</p>
<p>My bug performed a (sort of) distributed denial of service attack on (a subset of) Battle.net. My bad.</p>
<p>(Fun fact: being a programmer lets you make bigger mistakes. I think my mistake inconvenienced on the order of ten thousand people. That&#8217;s a lot, but laughably small on the scale of <a href="http://en.wikipedia.org/wiki/Therac-25">things</a> <a href="http://en.wikipedia.org/wiki/Mars_Climate_Orbiter">programmers</a> <a href="http://en.wikipedia.org/wiki/Year_2000_problem">have</a> <a href="http://en.wikipedia.org/wiki/2003_North_America_blackout">messed</a> <a href="http://www.debian.org/security/2008/dsa-1571">up</a>.)</p>
<p>&#8212;</p>
<h3>Discuss on <a href="https://news.ycombinator.com/item?id=5860071">Hacker News</a>, <a href="http://www.reddit.com/r/programming/comments/1g3sn3/my_bug_my_bad_accidentally_attacking_warcraft_3/">Reddit</a></h3>
<p>&#8212;</p>
]]></content:encoded>
			<wfw:commentRss>http://twistedoakstudios.com/blog/Post4281_my-bug-my-bad-3-accidentally-attacking-warcraft-3/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Collapsing Types vs Monads (followup)</title>
		<link>http://twistedoakstudios.com/blog/Post4130_collapsing-types-vs-monads-followup</link>
		<comments>http://twistedoakstudios.com/blog/Post4130_collapsing-types-vs-monads-followup#comments</comments>
		<pubDate>Tue, 04 Jun 2013 07:32:50 +0000</pubDate>
		<dc:creator>Craig Gidney</dc:creator>
				<category><![CDATA[Academic]]></category>
		<category><![CDATA[Explanation]]></category>
		<category><![CDATA[Types]]></category>

		<guid isPermaLink="false">http://twistedoakstudios.com/blog/?p=4130</guid>
		<description><![CDATA[Last week&#8217;s post about an automatically flattening future type received a lot of feedback. One of the running themes in the discussion was how collapsing types relate to monads: &#8220;Type operators that collapse when you nest them inside of themselves&#8221;, along with some conditions to actually work as you would expect, precisely describe the idea [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://twistedoakstudios.com/blog/Post4008_collapsing-futures-easy-to-use-hard-to-represent">Last week&#8217;s post</a> about an automatically flattening future type received a lot of feedback. One of the running themes in the discussion was how collapsing types relate to monads:</p>
<blockquote><p>&#8220;Type operators that collapse when you nest them inside of themselves&#8221;, along with some conditions to actually work as you would expect, precisely describe the idea of monad.<br />
<footer>gasche</footer>
</blockquote>
<blockquote><p>[...] This is the textbook definition of a monad.<br />
<footer>PasswordIsntHAMSTER</footer>
</blockquote>
<blockquote><p>monads, anyone?<br />
<footer>cheng81</footer>
</blockquote>
<blockquote><p>So the article and discussion here bring up a key question: what are the monads such that m (m a) and m a are isomorphic?<br />
<footer>sacundim</footer>
</blockquote>
<p>Given the mix of confusion and interest, I want to clear up how monads relate to collapsing types.</p>
<h3>Different</h3>
<p>Collapsing types aren&#8217;t the same thing as monads, and neither is a subset of the other. They are attributes that can apply independently.</p>
<p>A collapsing type is a type that satisfies the property that nesting it inside itself has no effect. A <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-561e33a4ff4fc9a57711d2cda43a8c71_l3.png" class="ql-img-inline-formula " alt="&#70;&#111;&#111;&#94;&#123;&#42;&#125;&#40;&#70;&#111;&#111;&#94;&#123;&#42;&#125;&#40;&#84;&#41;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="117" style="vertical-align: -4px;"/> must act identically to a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-99e87b5078ef9f33a303bbdb95af7d58_l3.png" class="ql-img-inline-formula " alt="&#70;&#111;&#111;&#94;&#123;&#42;&#125;&#40;&#84;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="64" style="vertical-align: -4px;"/> under all circumstances, for <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-6f2f23c67dcce9d6bb3fb42986d3ab48_l3.png" class="ql-img-inline-formula " alt="&#70;&#111;&#111;&#94;&#123;&#42;&#125;" title="Rendered by QuickLaTeX.com" height="13" width="38" style="vertical-align: 0px;"/> to be a collapsing type.</p>
<p>A monad is <a href="http://en.wikipedia.org/wiki/Monad_(functional_programming)#fmap_and_join">a type that supports three operations</a>: wrapping, transforming, and flattening (more typically called <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-6635fb8dadbd520619b8b389f8fa0d1d_l3.png" class="ql-img-inline-formula " alt="&#114;&#101;&#116;&#117;&#114;&#110;" title="Rendered by QuickLaTeX.com" height="12" width="53" style="vertical-align: 0px;"/>, <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-63ec2f4d7b6f45ef5210be501d413fb7_l3.png" class="ql-img-inline-formula " alt="&#102;&#109;&#97;&#112;" title="Rendered by QuickLaTeX.com" height="16" width="45" style="vertical-align: -4px;"/>, and <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f9d29a65e7e2d810b3c9a7d6a4b6246c_l3.png" class="ql-img-inline-formula " alt="&#106;&#111;&#105;&#110;" title="Rendered by QuickLaTeX.com" height="16" width="35" style="vertical-align: -4px;"/> respectively). The operations must also satisfy a few work-in-the-obvious-way-please rules.</p>
<p>If you tell me that <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-6f2f23c67dcce9d6bb3fb42986d3ab48_l3.png" class="ql-img-inline-formula " alt="&#70;&#111;&#111;&#94;&#123;&#42;&#125;" title="Rendered by QuickLaTeX.com" height="13" width="38" style="vertical-align: 0px;"/> is a collapsing type, I still don&#8217;t know if the type supports the operations necessary to make it a monad. Collapsing types <em>technically</em> support flattening, in that a proper <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f9d29a65e7e2d810b3c9a7d6a4b6246c_l3.png" class="ql-img-inline-formula " alt="&#106;&#111;&#105;&#110;" title="Rendered by QuickLaTeX.com" height="16" width="35" style="vertical-align: -4px;"/> method doesn&#8217;t have to make any changes. However, collapsing types are not required to support wrapping or transforming.</p>
<p>Conversely, if you tell me that <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-edaeeb1b835cb2fcc1970c255c271308_l3.png" class="ql-img-inline-formula " alt="&#66;&#97;&#114;" title="Rendered by QuickLaTeX.com" height="12" width="31" style="vertical-align: 0px;"/> is a monadic type, I still don&#8217;t know if it satisfies the condition <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-ff922697bcf88d995dee06981ea83649_l3.png" class="ql-img-inline-formula " alt="&#106;&#111;&#105;&#110;&#95;&#123;&#66;&#97;&#114;&#125;&#32;&#61;&#32;&#73;&#100;&#101;&#110;&#116;&#105;&#116;&#121;&#70;&#117;&#110;&#99;&#116;&#105;&#111;&#110;" title="Rendered by QuickLaTeX.com" height="17" width="224" style="vertical-align: -4px;"/> needed to qualify it as a collapsing type. Monads are not required to have <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f9d29a65e7e2d810b3c9a7d6a4b6246c_l3.png" class="ql-img-inline-formula " alt="&#106;&#111;&#105;&#110;" title="Rendered by QuickLaTeX.com" height="16" width="35" style="vertical-align: -4px;"/> operations that change nothing.</p>
<h3>Examples</h3>
<p>There are non-collapsing non-monadic types, collapsing non-monadic types, non-collapsing monadic types, and collapsing monadic types. Just to really drive home that &#8220;collapsing&#8221; is separate from &#8220;monadic&#8221;, lets go over an example of each.</p>
<p>An example of a collapsing monadic type is <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-69ae43d9b78d2767df7af44c242d691e_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;" title="Rendered by QuickLaTeX.com" height="13" width="63" style="vertical-align: 0px;"/>, from last week&#8217;s post.</p>
<p>An example of a non-collapsing monadic type is <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-87b24fc07082713f74318051967edaee_l3.png" class="ql-img-inline-formula " alt="&#76;&#105;&#115;&#116;" title="Rendered by QuickLaTeX.com" height="12" width="32" style="vertical-align: 0px;"/>. You can wrap anything into a list, transform the items in a list, and flatten lists of lists <em>but</em> a list of lists of integers is not the same as a list of integers.</p>
<p>An example of a collapsing non-monadic type is a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-a58cc0fc3027a97f2eda3ddeee1c1c24_l3.png" class="ql-img-inline-formula " alt="&#82;&#101;&#109;&#111;&#116;&#101;" title="Rendered by QuickLaTeX.com" height="12" width="61" style="vertical-align: 0px;"/> type representing an unknown value stored on a remote server, where the details of the server potentially using a further-remote server are hidden (meaning you treat a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-bc271aae0fb9b7c43cc6bfad4ce3b44f_l3.png" class="ql-img-inline-formula " alt="&#82;&#101;&#109;&#111;&#116;&#101;&#40;&#82;&#101;&#109;&#111;&#116;&#101;&#40;&#84;&#41;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="161" style="vertical-align: -4px;"/> exactly like a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-3edf4e7258026f92bb4c0409ba31895f_l3.png" class="ql-img-inline-formula " alt="&#82;&#101;&#109;&#111;&#116;&#101;&#40;&#84;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="86" style="vertical-align: -4px;"/>). If the server doesn&#8217;t allow you to apply arbitrary operations to remote values, or create arbitrary remote values, then <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-a58cc0fc3027a97f2eda3ddeee1c1c24_l3.png" class="ql-img-inline-formula " alt="&#82;&#101;&#109;&#111;&#116;&#101;" title="Rendered by QuickLaTeX.com" height="12" width="61" style="vertical-align: 0px;"/> is not a monad.</p>
<p>An example of a non-collapsing non-monadic type is <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-712336464c51f56c00067bd3607bece5_l3.png" class="ql-img-inline-formula " alt="&#83;&#113;&#117;&#97;&#114;&#101;&#77;&#97;&#116;&#114;&#105;&#120;" title="Rendered by QuickLaTeX.com" height="16" width="116" style="vertical-align: -4px;"/>. It&#8217;s not a collapsible type, because a matrix of matrices of booleans is distinct from a matrix of booleans. It&#8217;s not a monad unless you specify a flattening operation, but you&#8217;ll find there aren&#8217;t any nice ones to pick because you can&#8217;t preserve the number of values. For example, properly flattening <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-de97fcd7f6d7b26e44c7f3b92fc80b7b_l3.png" class="ql-img-inline-formula " alt="&#92;&#108;&#101;&#102;&#116;&#124;&#32;&#92;&#98;&#101;&#103;&#105;&#110;&#123;&#97;&#114;&#114;&#97;&#121;&#125;&#123;&#99;&#99;&#125;&#32;&#92;&#108;&#101;&#102;&#116;&#124;&#32;&#48;&#32;&#92;&#114;&#105;&#103;&#104;&#116;&#124;&#32;&#38;&#32;&#92;&#108;&#101;&#102;&#116;&#124;&#32;&#49;&#32;&#92;&#114;&#105;&#103;&#104;&#116;&#124;&#32;&#92;&#92;&#32;&#92;&#108;&#101;&#102;&#116;&#124;&#32;&#92;&#98;&#101;&#103;&#105;&#110;&#123;&#97;&#114;&#114;&#97;&#121;&#125;&#123;&#99;&#99;&#125;&#32;&#50;&#32;&#38;&#32;&#51;&#32;&#92;&#92;&#32;&#52;&#32;&#38;&#32;&#53;&#32;&#92;&#101;&#110;&#100;&#123;&#97;&#114;&#114;&#97;&#121;&#125;&#32;&#92;&#114;&#105;&#103;&#104;&#116;&#124;&#32;&#38;&#32;&#92;&#108;&#101;&#102;&#116;&#124;&#32;&#54;&#32;&#92;&#114;&#105;&#103;&#104;&#116;&#124;&#32;&#92;&#101;&#110;&#100;&#123;&#97;&#114;&#114;&#97;&#121;&#125;&#32;&#92;&#114;&#105;&#103;&#104;&#116;&#124;" title="Rendered by QuickLaTeX.com" height="65" width="121" style="vertical-align: -28px;"/> would require that seven be a square number (it&#8217;s not).</p>
<p><span style="font-size:x-small;"><em>Side note</em>: <em>Technically</em> you could make SquareMatrix into a monad by specifying a poor flattening operator, and so you might be tempted to say SquareMatrix is a monad. Don&#8217;t do it. Under that view, every type ever is a monad. Given a type T, you can make it a useless monad by picking a value v of type T and defining join, fmap and return to all unconditionally return v.</span></p>
<h3>Similar</h3>
<p>Monads and collapsing types are different, but still related.</p>
<p><em>In practice</em>, collapsing types you encounter will probably be monads. Mainly because most of them will be related to eventual results (e.g. <a href="https://github.com/promises-aplus/promises-spec">promises/A+</a> in JavaScript, <a href="http://twistedmatrix.com/trac/">Twisted Python</a> in Python, <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh780559.aspx">ppltasks for windows store apps</a> in C++).</p>
<p><em>In theory</em>, you can start from any monad <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-1778ed84ccb7648361d5189f9392cf06_l3.png" class="ql-img-inline-formula " alt="&#70;&#111;&#111;" title="Rendered by QuickLaTeX.com" height="12" width="32" style="vertical-align: 0px;"/> (which may not be a collapsing type)  and <em>derive</em> a related collapsing+monadic type <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-6f2f23c67dcce9d6bb3fb42986d3ab48_l3.png" class="ql-img-inline-formula " alt="&#70;&#111;&#111;&#94;&#123;&#42;&#125;" title="Rendered by QuickLaTeX.com" height="13" width="38" style="vertical-align: 0px;"/> by making the application of <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f9d29a65e7e2d810b3c9a7d6a4b6246c_l3.png" class="ql-img-inline-formula " alt="&#106;&#111;&#105;&#110;" title="Rendered by QuickLaTeX.com" height="16" width="35" style="vertical-align: -4px;"/> automatic. It&#8217;s what I did with <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-723cab44113019f883f78b59578c83fc_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;" title="Rendered by QuickLaTeX.com" height="12" width="57" style="vertical-align: 0px;"/> last week. All the methods on <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-69ae43d9b78d2767df7af44c242d691e_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;" title="Rendered by QuickLaTeX.com" height="13" width="63" style="vertical-align: 0px;"/> did internal checks to see if flattening was necessary or not, to make a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-3711a72a3d04cdbe344872f2398716b5_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#84;&#41;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="170" style="vertical-align: -4px;"/> act exactly like a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-26f2dc372f52226c6c69317e6aa82eca_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#84;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="91" style="vertical-align: -4px;"/>. This derivation makes more practical sense with some types (<img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-723cab44113019f883f78b59578c83fc_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;" title="Rendered by QuickLaTeX.com" height="12" width="57" style="vertical-align: 0px;"/>, <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-25d9cfe565759e5874628fc0a13c7336_l3.png" class="ql-img-inline-formula " alt="&#77;&#97;&#121;&#72;&#97;&#118;&#101;&#70;&#97;&#105;&#108;&#101;&#100;" title="Rendered by QuickLaTeX.com" height="17" width="134" style="vertical-align: -4px;"/>, <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-7a0888c15a439f11322a7784ea7f27b7_l3.png" class="ql-img-inline-formula " alt="&#79;&#98;&#115;&#101;&#114;&#118;&#97;&#98;&#108;&#101;" title="Rendered by QuickLaTeX.com" height="13" width="87" style="vertical-align: 0px;"/>, <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-79688720985de48fa0e196de6e08d26b_l3.png" class="ql-img-inline-formula " alt="&#77;&#97;&#121;&#72;&#97;&#118;&#101;&#67;&#97;&#110;&#99;&#101;&#108;&#108;&#101;&#100;" title="Rendered by QuickLaTeX.com" height="17" width="160" style="vertical-align: -4px;"/>) than it does with others (<img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-7ef448a5ef88114fcada3676ec95482f_l3.png" class="ql-img-inline-formula " alt="&#78;&#117;&#108;&#108;&#97;&#98;&#108;&#101;" title="Rendered by QuickLaTeX.com" height="13" width="68" style="vertical-align: 0px;"/>, <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-87b24fc07082713f74318051967edaee_l3.png" class="ql-img-inline-formula " alt="&#76;&#105;&#115;&#116;" title="Rendered by QuickLaTeX.com" height="12" width="32" style="vertical-align: 0px;"/>, <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-59d1cc759434b4ff0014ce13fbd36878_l3.png" class="ql-img-inline-formula " alt="&#84;&#114;&#101;&#101;" title="Rendered by QuickLaTeX.com" height="12" width="37" style="vertical-align: 0px;"/>, <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-45ee16c72cea26e0c4b72808ac90d410_l3.png" class="ql-img-inline-formula " alt="&#80;&#97;&#114;&#115;&#101;&#114;" title="Rendered by QuickLaTeX.com" height="12" width="56" style="vertical-align: 0px;"/>).</p>
<p>Warning: a potential issue with the above derivation is the creation of self-referencing flattening cycles, where you end up with a type nested inside itself infinitely many times and keep trying to unwrap it. For example, adding the following three lines to my <a href="http://pythonfiddle.com/collapsing-future-demo/">collapsing future&#8217;s python fiddle</a> causes a flattening cycle:</p>
<pre><code class="prettyprint">cycle = Future()
cycle.trySetResult(cycle)
cycle.continueWith(out) #never halts</code></pre>
<p>It&#8217;s probably a good idea to have runtime checks for this issue. Compile-time checks would be even better, but beware accidentally solving the halting problem.</p>
<h3>Summary</h3>
<p>Collapsing types are not the same thing as monads.</p>
<p>You can transform any monadic type into a collapsing monadic type.</p>
<p>Next week: less type theory.</p>
<p>&#8212;</p>
<h3>Discuss on <a href="http://www.reddit.com/r/programming/comments/1fn0zi/collapsing_types_vs_monads_followup_to_collapsing/">Reddit</a></h3>
<p>&#8212;</p>
]]></content:encoded>
			<wfw:commentRss>http://twistedoakstudios.com/blog/Post4130_collapsing-types-vs-monads-followup/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Collapsing Futures: Easy to Use, Hard to Represent</title>
		<link>http://twistedoakstudios.com/blog/Post4008_collapsing-futures-easy-to-use-hard-to-represent</link>
		<comments>http://twistedoakstudios.com/blog/Post4008_collapsing-futures-easy-to-use-hard-to-represent#comments</comments>
		<pubDate>Tue, 28 May 2013 06:12:14 +0000</pubDate>
		<dc:creator>Craig Gidney</dc:creator>
				<category><![CDATA[Academic]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Types]]></category>

		<guid isPermaLink="false">http://twistedoakstudios.com/blog/?p=4008</guid>
		<description><![CDATA[Type systems are useful things, but they can also over-constrain how you represent values. In this post I discuss a useful kind of type that&#8217;s difficult to represent in the type systems of most popular languages: types that &#8220;collapse&#8221; when you nest them inside of themselves. Collapsing the Eventual Eventual Future Suppose you have a [...]]]></description>
				<content:encoded><![CDATA[<p>Type systems are useful things, but they can also over-constrain how you represent values. In this post I discuss a useful kind of type that&#8217;s difficult to represent in the type systems of most popular languages: types that &#8220;collapse&#8221; when you nest them inside of themselves.</p>
<h3>Collapsing the Eventual Eventual Future</h3>
<p>Suppose you have a <a href="http://en.wikipedia.org/wiki/Futures_and_promises">Future</a>: a representation of a value that may not be computed yet but will eventually be ready. Further suppose the eventual value of that future (call it <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-53758a55e8fcf7de30646946d56717a8_l3.png" class="ql-img-inline-formula " alt="&#70;&#95;&#123;&#111;&#117;&#116;&#101;&#114;&#125;" title="Rendered by QuickLaTeX.com" height="15" width="43" style="vertical-align: -3px;"/>) is itself a future (call it <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-eb320baab12124c29068f3a6c9064e87_l3.png" class="ql-img-inline-formula " alt="&#70;&#95;&#123;&#105;&#110;&#110;&#101;&#114;&#125;" title="Rendered by QuickLaTeX.com" height="15" width="44" style="vertical-align: -3px;"/>), and that the eventual value of <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-eb320baab12124c29068f3a6c9064e87_l3.png" class="ql-img-inline-formula " alt="&#70;&#95;&#123;&#105;&#110;&#110;&#101;&#114;&#125;" title="Rendered by QuickLaTeX.com" height="15" width="44" style="vertical-align: -3px;"/> is the integer <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-99ef48eeaa52afd5965a742f9aed12cd_l3.png" class="ql-img-inline-formula " alt="&#49;" title="Rendered by QuickLaTeX.com" height="13" width="7" style="vertical-align: -1px;"/>. Said another way, <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-53758a55e8fcf7de30646946d56717a8_l3.png" class="ql-img-inline-formula " alt="&#70;&#95;&#123;&#111;&#117;&#116;&#101;&#114;&#125;" title="Rendered by QuickLaTeX.com" height="15" width="43" style="vertical-align: -3px;"/> is eventually <em>eventually</em> <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-99ef48eeaa52afd5965a742f9aed12cd_l3.png" class="ql-img-inline-formula " alt="&#49;" title="Rendered by QuickLaTeX.com" height="13" width="7" style="vertical-align: -1px;"/>. Notice that &#8220;eventually&#8221; was repeated twice.</p>
<p>An interesting property of the word &#8220;eventually&#8221; is that repeating it twice doesn&#8217;t seem to change the literal meaning of sentences. Saying something will eventually <em>eventually</em> happen is the same as saying it will just eventually happen. Doubly-eventual is the same as singly-eventual. However, your typical implementation of a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-d2664b3cea8e77cd96d8c2b14e21705f_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#40;&#84;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="83" style="vertical-align: -4px;"/> type will not have this &#8220;doubly is the same as singly&#8221; property. You&#8217;ll find that that <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-c14740aa4dcbb905620fa03867fdc53b_l3.png" class="ql-img-inline-formula " alt="&#70;&#95;&#123;&#111;&#117;&#116;&#101;&#114;&#125;&#46;&#86;&#97;&#108;&#117;&#101;&#32;&#92;&#110;&#101;&#113;&#32;&#49;" title="Rendered by QuickLaTeX.com" height="17" width="129" style="vertical-align: -4px;"/>, even though <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-53758a55e8fcf7de30646946d56717a8_l3.png" class="ql-img-inline-formula " alt="&#70;&#95;&#123;&#111;&#117;&#116;&#101;&#114;&#125;" title="Rendered by QuickLaTeX.com" height="15" width="43" style="vertical-align: -3px;"/> is eventually <em>eventually</em> <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-99ef48eeaa52afd5965a742f9aed12cd_l3.png" class="ql-img-inline-formula " alt="&#49;" title="Rendered by QuickLaTeX.com" height="13" width="7" style="vertical-align: -1px;"/>, because <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-319a9bf7c033e426b673140fb9066e05_l3.png" class="ql-img-inline-formula " alt="&#70;&#95;&#123;&#111;&#117;&#116;&#101;&#114;&#125;&#46;&#86;&#97;&#108;&#117;&#101;" title="Rendered by QuickLaTeX.com" height="16" width="97" style="vertical-align: -3px;"/> is a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-8f33166e0fb42e06fdabd7c6f7843b7a_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#40;&#105;&#110;&#116;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="93" style="vertical-align: -4px;"/> instead of an <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-823288aec3984376b55b347748d0b924_l3.png" class="ql-img-inline-formula " alt="&#105;&#110;&#116;" title="Rendered by QuickLaTeX.com" height="12" width="23" style="vertical-align: 0px;"/>.</p>
<p>Can we implement a variant of <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-d2664b3cea8e77cd96d8c2b14e21705f_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#40;&#84;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="83" style="vertical-align: -4px;"/>, a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-26f2dc372f52226c6c69317e6aa82eca_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#84;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="91" style="vertical-align: -4px;"/>, that <em>does</em> respect that singly-eventual should be the same as doubly-eventual? This would be useful because it would mean we wouldn&#8217;t have to track the level of nesting in order to write correct code (which is <em>particularly</em> useful in dynamic languages and languages without generics, where the compiler won&#8217;t catch nesting-level mistakes).</p>
<p><em>Side note: If you think of <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-69ae43d9b78d2767df7af44c242d691e_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;" title="Rendered by QuickLaTeX.com" height="13" width="63" style="vertical-align: 0px;"/> as a function that takes a type and returns a type, then calling <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-69ae43d9b78d2767df7af44c242d691e_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;" title="Rendered by QuickLaTeX.com" height="13" width="63" style="vertical-align: 0px;"/> a collapsing type is equivalent to saying its function is <a href="http://en.wikipedia.org/wiki/Idempotence">idempotent</a>.</em></p>
<p>If we try to implement <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-69ae43d9b78d2767df7af44c242d691e_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;" title="Rendered by QuickLaTeX.com" height="13" width="63" style="vertical-align: 0px;"/> in C# or in Java, we&#8217;ll run into a bit of trouble when we try to specify the type of the value in a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-26f2dc372f52226c6c69317e6aa82eca_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#84;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="91" style="vertical-align: -4px;"/>. It&#8217;s a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-ec7698f8d74893529c6817c17026537b_l3.png" class="ql-img-inline-formula " alt="&#84;" title="Rendered by QuickLaTeX.com" height="12" width="13" style="vertical-align: 0px;"/>, unless <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-ec7698f8d74893529c6817c17026537b_l3.png" class="ql-img-inline-formula " alt="&#84;" title="Rendered by QuickLaTeX.com" height="12" width="13" style="vertical-align: 0px;"/> is a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-9a37f96f54a06128038b9ccd4a56a20a_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#84;&#95;&#50;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="96" style="vertical-align: -4px;"/> in which case it&#8217;s a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-2e61fa68c269094e344d36c62928de3e_l3.png" class="ql-img-inline-formula " alt="&#84;&#95;&#50;" title="Rendered by QuickLaTeX.com" height="15" width="17" style="vertical-align: -3px;"/>, unless <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-2e61fa68c269094e344d36c62928de3e_l3.png" class="ql-img-inline-formula " alt="&#84;&#95;&#50;" title="Rendered by QuickLaTeX.com" height="15" width="17" style="vertical-align: -3px;"/> is&#8230; you get the idea. Their type systems can&#8217;t express these sorts of conditions, although more flexible type systems can (I think you can do it with templates in C++, for example), so we&#8217;re forced to give up on collapsing or give up on knowing the type of value coming out of a future.</p>
<p>In a dynamic language, or in a language without generics, this trade-off doesn&#8217;t exist. The language designers have made the choice for us: the type of value coming out of a future can&#8217;t be specified. This makes implementations in such languages feel much more natural.</p>
<h3>Python Implementation</h3>
<p>I implemented a collapsing future type in python, <a href="http://pythonfiddle.com/collapsing-future-demo/">which you can play with on PythonFiddle</a>. It works by checking the types of results at runtime, and flattening them when they&#8217;re also futures. Here is the type:</p>
<pre><code class="prettyprint">### An eventual value that automatically flattens doubly-eventual results
class Future:
    ### Inits a new not-yet-specified future value
    def __init__(self):
        self.__continuations = []
        
    ### Registers a continuation to run when the flattened future value is ready
    ### Returns the continuation's future result
    def continueWith(self, continuation):
        # remember continuation, if result not provided yet
        if self.__continuations != None:
            r = Future()
            self.__continuations.append((continuation, r))
            return r
        
        # automatic flattening
        if isinstance(self.__result, Future):
            return self.__result.continueWith(continuation)

        # run continuation inline when already finished        
        r = Future()
        v = continuation(self.__result)
        r.trySetResult(v)
        return r
    
    ### Sets this future's value, if it has not yet been set.
    ### Causes all registered continuations to be run or handed off.
    def trySetResult(self, result):
        # already set?
        cs = self.__continuations
        if cs == None: return False;
        
        # state transition
        self.__continuations = None
        self.__result = result
        
        # perform or hand-off registered continuations
        for e in cs:
            continuation, future = e
            r = self.continueWith(continuation);
            future.trySetResult(r)
        
        return True</code></pre>
<p>If you read closely, you&#8217;ll notice that the above (not particularly efficient) implementation is itself (ab)using the fact that <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-69ae43d9b78d2767df7af44c242d691e_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;" title="Rendered by QuickLaTeX.com" height="13" width="63" style="vertical-align: 0px;"/> is a collapsing type. For example, when a future&#8217;s result is being set to a a future, the results of continuations are set directly to the results of handed-off continuations despite them having a different level of nesting.</p>
<p>Here&#8217;s some sample code that uses the above future type, demonstrating that you don&#8217;t have to care about the level of nesting:</p>
<pre><code class="prettyprint">f1 = Future()
f2 = Future()
f3 = f1.continueWith(lambda v1: f2.continueWith(lambda v2: v1 + v2))

def out(x): print x
f1.continueWith(lambda x: out("f1's result = " + x))
f2.continueWith(lambda x: out("f2's result = " + x))
f3.continueWith(lambda x: out("f3's result = " + x))

f1.trySetResult(f2)
f2.trySetResult('Hello')

# outputs: 
# f2's result = Hello
# f3's result = HelloHello
# f1's result = Hello
</code></pre>
<p>In the above code, <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-ba4066f9d9dadbebe5bd49b12c545a36_l3.png" class="ql-img-inline-formula " alt="&#102;&#50;" title="Rendered by QuickLaTeX.com" height="16" width="19" style="vertical-align: -4px;"/> has type <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-4ff589f19533008f37ff2584e5fcbbfd_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#83;&#116;&#114;&#105;&#110;&#103;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="131" style="vertical-align: -4px;"/> because its result is set to a string. <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-0d704dd05e1515afd9729570c9928ab0_l3.png" class="ql-img-inline-formula " alt="&#102;&#49;" title="Rendered by QuickLaTeX.com" height="16" width="19" style="vertical-align: -4px;"/> has type <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-b6bf33198ecb9a2fc90c146c1e1abf31_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#83;&#116;&#114;&#105;&#110;&#103;&#41;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="209" style="vertical-align: -4px;"/> because its result is set to be <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-ba4066f9d9dadbebe5bd49b12c545a36_l3.png" class="ql-img-inline-formula " alt="&#102;&#50;" title="Rendered by QuickLaTeX.com" height="16" width="19" style="vertical-align: -4px;"/>. <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-02dad18fb9949faeef4ebb0ba1b9fd78_l3.png" class="ql-img-inline-formula " alt="&#102;&#51;" title="Rendered by QuickLaTeX.com" height="16" width="20" style="vertical-align: -4px;"/> has type <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-e58f7face6d269aa4354afa1d444a830_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#83;&#116;&#114;&#105;&#110;&#103;&#41;&#41;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="288" style="vertical-align: -4px;"/>, for reasons related to continueWith returning a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-26f2dc372f52226c6c69317e6aa82eca_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#84;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="91" style="vertical-align: -4px;"/> when given a function that returns a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-ec7698f8d74893529c6817c17026537b_l3.png" class="ql-img-inline-formula " alt="&#84;" title="Rendered by QuickLaTeX.com" height="12" width="13" style="vertical-align: 0px;"/>.</p>
<p>Wait, why are we doing this complicated analysis? Because of the collapsing property, it&#8217;s dead obvious that they all have type <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-4ff589f19533008f37ff2584e5fcbbfd_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#83;&#116;&#114;&#105;&#110;&#103;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="131" style="vertical-align: -4px;"/>. The fact that <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-02dad18fb9949faeef4ebb0ba1b9fd78_l3.png" class="ql-img-inline-formula " alt="&#102;&#51;" title="Rendered by QuickLaTeX.com" height="16" width="20" style="vertical-align: -4px;"/>&#8216;s result prints out as <code>"HelloHello"</code>, instead of <code>&lt;__main__.Future instance at ...&gt;</code>, confirms it.</p>
<p>This is a level beyond having the compiler detect that you&#8217;ve made a nesting-level mistake. The mistake has been made <em>fundamentally impossible</em>, at least with respect to our future type on its own.</p>
<h3>Mixing With Others</h3>
<p>There are other types that can benefit from being made collapsible. For example, the &#8220;MayFail&#8221; and &#8220;MayBeCancelled&#8221; types I mentioned last week would work well as collapsing types, because you very rarely care &#8220;at what level&#8221; a failure or cancellation occurred. On the other hand, &#8220;List&#8221; would be a terrible collapsing type because you so often need to have a lists of lists. Another terrible candidate is &#8220;Maybe&#8221;, because you usually <em>do</em> care about &#8220;at what level&#8221; a value has been omitted.</p>
<p>One potential obstacle to having lots of collapsing types is mixing. A <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-bcf8d4d2a9ce53c51593178de2045676_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#77;&#97;&#121;&#70;&#97;&#105;&#108;&#94;&#123;&#42;&#125;&#40;&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#77;&#97;&#121;&#70;&#97;&#105;&#108;&#94;&#123;&#42;&#125;&#40;&#84;&#41;&#41;&#41;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="358" style="vertical-align: -4px;"/> won&#8217;t automatically collapse into a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-d9c84e7f60213265e9e17202127fa1ff_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#77;&#97;&#121;&#70;&#97;&#105;&#108;&#94;&#123;&#42;&#125;&#40;&#84;&#41;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="185" style="vertical-align: -4px;"/>, and so mixing may re-introduce the need to care about nesting level. This is particularly bad in the case of futures because they often represent operations that might fail, and so mixing will be endemic. Maybe it would be possible to have some sort of cross-type collapsing that applies in appropriate places&#8230; I really just don&#8217;t know yet.</p>
<h3>Summary</h3>
<p>A collapsing type transparently flattens itself when nested inside of itself. A <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-b6bf33198ecb9a2fc90c146c1e1abf31_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#83;&#116;&#114;&#105;&#110;&#103;&#41;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="209" style="vertical-align: -4px;"/> will act exactly identical to a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-4ff589f19533008f37ff2584e5fcbbfd_l3.png" class="ql-img-inline-formula " alt="&#70;&#117;&#116;&#117;&#114;&#101;&#94;&#123;&#42;&#125;&#40;&#83;&#116;&#114;&#105;&#110;&#103;&#41;" title="Rendered by QuickLaTeX.com" height="18" width="131" style="vertical-align: -4px;"/>.</p>
<p>Collapsing types are easy to use, because they make nesting-level mistakes impossible. Collapsing types are hard to represent, because their type can&#8217;t be specified in the type systems of most popular languages.</p>
<p>&#8212;</p>
<h3>Discuss on <a href="http://www.reddit.com/r/programming/comments/1f6or3/collapsing_futures_easy_to_use_hard_to_represent/">Reddit</a></h3>
<p>&#8212;</p>
]]></content:encoded>
			<wfw:commentRss>http://twistedoakstudios.com/blog/Post4008_collapsing-futures-easy-to-use-hard-to-represent/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Eventual Exceptions vs Programming in a Minimal Functional Style</title>
		<link>http://twistedoakstudios.com/blog/Post3858_eventual-exceptions-vs-programming-in-a-minimal-functional-style</link>
		<comments>http://twistedoakstudios.com/blog/Post3858_eventual-exceptions-vs-programming-in-a-minimal-functional-style#comments</comments>
		<pubDate>Wed, 22 May 2013 10:08:07 +0000</pubDate>
		<dc:creator>Craig Gidney</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Types]]></category>

		<guid isPermaLink="false">http://twistedoakstudios.com/blog/?p=3858</guid>
		<description><![CDATA[One of the downsides to exceptions that I&#8217;m becoming more sensitive to as time passes, at least as they are implemented in most languages (python, ruby, C#, C++, Java, VB, JavaScript, etc), is mixing poorly with a functional programming style. In this post, I&#8217;ll explore this issue from the perspective of eventual results / promises [...]]]></description>
				<content:encoded><![CDATA[<p>One of the downsides to <a href="http://en.wikipedia.org/wiki/Exception_handling">exceptions</a> that I&#8217;m becoming more sensitive to as time passes, at least as they are implemented in most languages (python, ruby, C#, C++, Java, VB, JavaScript, etc), is mixing poorly with a functional programming style.</p>
<p>In this post, I&#8217;ll explore this issue from the perspective of <a href="http://en.wikipedia.org/wiki/Futures_and_promises">eventual results / promises / futures</a>.</p>
<h3>Representing Eventual Results</h3>
<p>The standard promise/future/eventual-value type in .Net is called <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx"><code>Task&lt;T&gt;</code></a>.</p>
<p>Like all decent &#8216;eventual result&#8217; types, <code>Task&lt;T&gt;</code> supports or can support all the <a href="http://en.wikipedia.org/wiki/Monad_%28functional_programming%29#fmap_and_join">operations needed to qualify as a monad</a> (wrapping, transforming, flattening):</p>
<pre><code class="prettyprint">// wrapping
Task&lt;int&gt; wrapped = Task.FromResult(10);

Task&lt;bool&gt; wrapped2 = Task.FromResult(true);

// transforming
Task&lt;IPAddress&gt; transformed = from hostEntry in Dns.GetHostEntryAsync("example.com")
                              <a href="https://github.com/TwistedOakStudios/Twisted-Oak-Threading-Utilities/blob/master/TwistedOakThreading/Threading/TaskExtensions.cs#L106">select</a> hostEntry.AddressList.First();

Task&lt;Task&lt;TcpClient&gt;&gt; transformed2 = from address in projected
                                     select Tcp.ConnectAsync(address, 80);

// flattening
Task&lt;TcpClient&gt; flattened = transformed2.Unwrap();</code></pre>
<p>However, <code>Task&lt;T&gt;</code> is more complicated than strictly necessary. A simplest-possible eventual result, a <code>MinimalTask&lt;T&gt;</code>, would only be able to represent eventually succeeding with a value of type <code>T</code>. A <code>Task&lt;T&gt;</code>, on the other hand, can succeed with a value of type <code>T</code>, or fail with an exception, or even end up cancelled with no associated value. When you ask for a <code>Task&lt;T&gt;</code> you&#8217;re actually asking for a <code>MinimalTask&lt;MayFailWithException&lt;MayBeCancelled&lt;T&gt;&gt;&gt;</code>!</p>
<p>Of course, there are good practical reasons for <code>Task&lt;T&gt;</code> to be able to represent failure and cancellation. If you try to run a function asynchronously, and it throws an exception, it&#8217;s downright <em>useful</em> to have a place to put that exception. Most operations can fail. Most asynchronous operations can be cancelled. It makes sense to support those scenarios.</p>
<p>Notice that .Net having exceptions just leaked into how we represent eventual results.</p>
<p>All tasks can fail or be cancelled. That means <em>everything</em> that works with tasks must handle cancellation and faulting in an appropriate way. The flexibility is useful, but when it isn&#8217;t needed it unnecessarily complicates things and introduces opportunities for bugs. (Note similarities to the downsides of forcing all references to allow a null value.)</p>
<p>A good example of the trade-offs due to cancellable faultable tasks is the design of <code>Task.WhenAll</code>.</p>
<h3>Aggregating Eventual Results</h3>
<p><code>Task.WhenAll</code> takes a sequence of tasks and returns a task that completes when all of the tasks have completed. More exactly, once all of the tasks have completed, they are combined as follows. If any of the tasks failed, the resulting task fails with an aggregate exception containing all of the failures. Otherwise, if any of the tasks were cancelled, the resulting task ends up cancelled. Otherwise the resulting task succeeds with an array of the tasks&#8217; values.</p>
<p>Notice that, if tasks couldn&#8217;t represent exceptions, the above description would be a lot simpler. It wouldn&#8217;t discuss how to aggregate exceptions, it wouldn&#8217;t note that exceptions take priority over cancellations, etc. The majority of the method&#8217;s specification is made up of details that aren&#8217;t directly related to eventual-ness, and could exist elsewhere.</p>
<p>A hypothetical <code>WhenAll</code> method for a hypothetical <code>MinimalTask&lt;T&gt;</code> type would be simpler than <code>Task.WhenAll</code>. Since there&#8217;s no exceptions or cancellations, there&#8217;s no need to specify the details of combining exceptions, whether exceptions take priority over cancellation, and etc. <code>MinimalTask.WhenAll</code> &#8220;flips&#8221; the order of many-ness and eventual-ness in the obvious way, and <em>that&#8217;s it</em>.</p>
<p>Can we implement <code>Task.WhenAll</code> in terms of the hypothetical <code>MinimalTask.WhenAll</code>? Keeping in mind that a <code>Task&lt;T&gt;</code> is essentially a <code>MinimalTask&lt;MayFail&lt;May&lt;T&gt;&gt;&gt;</code>, it&#8217;s actually pretty easy. All of the details of how to aggregate should already be in the types designed to represent potential-failure and potential-cancellation, so the method ends up being downright simple:</p>
<pre><code class="prettyprint">
MinimalTask&lt;MayFail&lt;May&lt;T[]&gt;&gt;&gt; WhenAllMay(this IEnumerable&lt;MinimalTask&lt;MayFail&lt;May&lt;T&gt;&gt;&gt;&gt; tasks) {
    return from v1 in MinimalTask.WhenAll(tasks) // v1: MayFail&lt;May&lt;T&gt;&gt;[]
           from v2 in MayFail.WhenAll(v1)        // v2: May&lt;T&gt;[]
           from v3 in May.WhenAll(v2)            // v3: T[]
           select v3;                            // result: T[] in May in MayFail in MinimalTask
}</code></pre>
<p>(Interesting fact: actually this method is in a sense <em>not even necessary</em> because <a href="http://twistedoakstudios.com/blog/Post867_how-would-i-even-use-a-monad-in-c">all WhenAll methods can be implemented with the same code</a>.)</p>
<p>By separating eventual-ness from may-cancel-ness and may-fail-ness, we avoid repeating the details of how to aggregate exceptions and cancellations.</p>
<h3>Wrapping Up</h3>
<p>The technical term for a type that represents &#8216;is a result of type T or else a failure&#8217; is &#8220;<a href="http://learnyouahaskell.com/for-a-few-monads-more#error">Error Monad</a>&#8221; (it&#8217;s a monad because you can wrap, transform, and flatten may-have-failed-ness).</p>
<p><del datetime="2013-05-22T16:59:46+00:00">[Aside: I can't believe the best 'error monad' link I could find was technical Haskell documentation. If anyone has a more informative link, I would appreciate it.]</del> (<a href="http://monads.haskell.cz/html/errormonad.html">old link</a>, <a href="http://www.reddit.com/r/programming/comments/1etquz/eventual_exceptions_vs_programming_in_a_minimal/ca3skhn">new link suggested by DR6</a>)</p>
<p>Unfortunately, although it may be aesthetically pleasing and proper functional style to separate may-fail-ness from eventual-ness, I&#8217;m not sure if it&#8217;s a good idea or not in imperative languages with exceptions. The problem is that <em>they already have a way to represent failure</em>, and the easiest way to fight your language is to add second way to do something included &#8220;in the box&#8221;.</p>
<h3>Summary</h3>
<p>Because .Net has exceptions, <code>Task&lt;T&gt;</code> is forced to represent exceptional results. Because <code>Task&lt;T&gt;</code> can represent exceptional results, async methods are often more complicated than necessary (making them harder to work with, functionally). Separating the &#8216;might fail&#8217; part out of <code>Task&lt;T&gt;</code> and into its own type is one way to avoid the complications when they aren&#8217;t necessary. However, because .Net has exceptions, doing so is potentially bad form.</p>
<p>That&#8217;s why I consider tasks to be an example of what I mean when I say exceptions mix poorly with a functional style. They add complications to otherwise-simple functional types.</p>
<p>&#8212;</p>
<h3>Discuss on <a href="http://www.reddit.com/r/programming/comments/1etquz/eventual_exceptions_vs_programming_in_a_minimal/">Reddit</a></h3>
<p>&#8212;</p>
]]></content:encoded>
			<wfw:commentRss>http://twistedoakstudios.com/blog/Post3858_eventual-exceptions-vs-programming-in-a-minimal-functional-style/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Mystery of Flunf</title>
		<link>http://twistedoakstudios.com/blog/Post3769_the-mystery-of-flunf</link>
		<comments>http://twistedoakstudios.com/blog/Post3769_the-mystery-of-flunf#comments</comments>
		<pubDate>Tue, 14 May 2013 08:01:31 +0000</pubDate>
		<dc:creator>Craig Gidney</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://twistedoakstudios.com/blog/?p=3769</guid>
		<description><![CDATA[This week, I have manufactured a mystery. Returning readers might see the issue right away. Don&#8217;t worry, it&#8217;s got nothing to do with unicode. Flunf? Why the flunf does the following C# code print &#8216;False&#8217;? var flunf = 98765432f; var sortedList = new List&#60;double&#62; { flunf + 1, flunf + 3, }; var valueToInsert = [...]]]></description>
				<content:encoded><![CDATA[<p>This week, I have manufactured a mystery.</p>
<p>Returning readers might see the issue right away. Don&#8217;t worry, it&#8217;s got nothing to do with unicode.</p>
<h3>Flunf?</h3>
<p>Why the flunf does the <a href="http://ideone.com/Tq7H0X">following C# code print &#8216;False&#8217;</a>?</p>
<pre><code class="prettyprint">var flunf = 98765432f;

var sortedList = new List&lt;double&gt; {
    flunf + 1, 
    flunf + 3, 
};
var valueToInsert = flunf + 2;
var indexOfInsert = sortedList.TakeWhile(e => e < flunf + 2).Count();
sortedList.Insert(indexOfInsert, valueToInsert);

var stayedSorted = sortedList.SequenceEqual(sortedList.OrderBy(e => e));
Console.WriteLine(stayedSorted); // prints 'False'</code></pre>
<p>(You should check your solution against the &#8216;likely mistake&#8217; entry below.)</p>
<h3>Hints</h3>
<p>Hint: <font style="background-color:black; color:black;">The fact that flunf is a float matters, but <em>how</em> it matters is the real puzzle.</font></p>
<p>Hint: <font style="background-color:black; color:black;">sortedList is [98765433, 98765432, 98765435] in the end.</font></p>
<p>Hint: <font style="background-color:black; color:black;">The type of float+int is float.</font></p>
<p>Spoiler: <font style="background-color:black; color:black;">The preceeding hint is correct, but very misleading.</font></p>
<p>Likely Mistake: <font style="background-color:black; color:black;">If limited precision was the only issue, everything would round to flunf and be trivially sorted.</font></p>
<p>Disclaimer: <font style="background-color:black; color:black;">It is possible that, in the future or on other machines, the list will actually end up sorted and &#8216;True&#8217; will be printed. In that case, the puzzle is why <strong>and under what conditions</strong> could the list end up not sorted? I assure you that the code prints &#8216;False&#8217; on my machine.</font><br />
&#8212;</p>
<h3>Discuss on <a href="http://www.reddit.com/r/programming/comments/1eaxj6/the_mystery_of_flunf_a_floating_point_puzzle/">Reddit</a></h3>
<p>&#8212;</p>
]]></content:encoded>
			<wfw:commentRss>http://twistedoakstudios.com/blog/Post3769_the-mystery-of-flunf/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Explain it like I&#8217;m Five: The Socialist Millionaire Problem and Secure Multi-Party Computation</title>
		<link>http://twistedoakstudios.com/blog/Post3724_explain-it-like-im-five-the-socialist-millionaire-problem-and-secure-multi-party-computation</link>
		<comments>http://twistedoakstudios.com/blog/Post3724_explain-it-like-im-five-the-socialist-millionaire-problem-and-secure-multi-party-computation#comments</comments>
		<pubDate>Tue, 07 May 2013 10:02:08 +0000</pubDate>
		<dc:creator>Craig Gidney</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Explanation]]></category>

		<guid isPermaLink="false">http://twistedoakstudios.com/blog/?p=3724</guid>
		<description><![CDATA[Last week, I talked about interesting concepts in computer science. Most of the resulting discussion revolved around the halting problem, but one person asked for clarification about Yao&#8217;s Millionaires&#8217; Problem. What is it? How does secure multi-party computation allow you to solve it? Why is the solution on Wikipedia so complicated? So, this week, I&#8217;m [...]]]></description>
				<content:encoded><![CDATA[<p>Last week, I talked about interesting concepts in computer science. Most of the resulting discussion revolved around the halting problem, but one person asked for clarification about <a href="http://en.wikipedia.org/wiki/Yao%27s_Millionaires%27_Problem">Yao&#8217;s Millionaires&#8217; Problem</a>. What is it? How does secure multi-party computation allow you to solve it? Why is the solution on Wikipedia so complicated?</p>
<p>So, this week, I&#8217;m going to explain how to solve millionaire-style problems without resorting to any sort of cryptography.</p>
<h3>The Problem: Socialist Millionaires</h3>
<p>Two employees, Alice and Bob, want to know if they are being paid fair wages. They do the same amount of work at the same level of quality, but they suspect that their employer might be taking advantage of one of them.</p>
<p>The easiest way to determine if they make the same amount of money per hour is for both to say &#8220;I make X dollars per hour&#8221;. Unfortunately, although Alice and Bob trust each other, they are very private about their income. They consider it a huge social faux pas to reveal how much money you make. The possibility of <a href="http://en.wikipedia.org/wiki/Common_knowledge_%28logic%29">common knowledge</a> of who makes more money is just&#8230; too uncomfortably awkward to bear.</p>
<p>Not only do Alice and Bob refuse to reveal how much money they make, to each other or a trusted third party, but they&#8217;re a bit technophobic and refuse to enter the information into a computer for fear of it being logged.</p>
<p>How can they find out if they&#8217;re being paid fairly, without risking an awkward situation and without using computers? With locked suggestion boxes, of course!</p>
<h3>The Solution: Use Locked Suggestions Boxes</h3>
<p>Suppose Alice and Bob each might be making either 10, 20, 30, or 40 $/hour. We&#8217;ll arbitrarily say that Alice makes 30$/hour and Bob makes 20$/hour.</p>
<ol>
<li>Bob goes to an office supply store and buys four lockable suggestion boxes (with different matching keys). He labels the four boxes as 10$, 20$, 30$, and 40$.
<p><img src="http://i.imgur.com/LYJLH4n.png" alt="Four labelled and locked suggestion boxes" /></p>
<li>Bob discards all of the keys except the key for the 20$ box (because that&#8217;s how much he makes per hour).
<p><img src="http://i.imgur.com/prmOmIh.png" alt="Bob discards all but the 20$ key" /></p>
<li>Bob gives the locked suggestion boxes to Alice. In private, Alice puts a slip of paper saying &#8216;yes&#8217; into the 30$ box (because that&#8217;s how much she makes per hour). She puts slips of paper saying &#8216;no&#8217; into the other boxes.
<p><img src="http://i.imgur.com/jGgdBcW.png" alt="Alice puts a slip of paper in each box" /></p>
<li>Alice gives the boxes back to Bob. In private, Bob uses his key to unlock the 20$ box and get the slip of paper inside.
<p><img src="http://i.imgur.com/hCfs7iS.png" alt="Bob finds out they don't make the same amount" /></p>
<li>Bob sees that the slip of paper says &#8216;no&#8217;, meaning Alice doesn&#8217;t make 20$/hour like he does. He tells Alice they don&#8217;t make the same amount of money.
<li>Bob now knows that Alice doesn&#8217;t make 20$/hour, but hasn&#8217;t learned if she makes 10, 30, or 40 $/hour. Similarly, Alice now knows Bob doesn&#8217;t make 30$/hour, but hasn&#8217;t learned if he makes 10, 20, or 40 $/hour.
</ol>
<h3>Oblivious Transfer</h3>
<p>The technical term for what Alice and Bob did in the  previous example is <a href="http://en.wikipedia.org/wiki/Oblivious_transfer">oblivious transfer</a>. Alice <em>transferred</em> many messages to Bob, but is <em>oblivious</em> to which single message Bob received. Alice sent an answer for every possible amount of money Bob might make, but Bob only received the answer corresponding to how much money he actually makes.</p>
<p>Note that there&#8217;s a certain amount of trust required for this to work. If Bob is going to lie and pretend he makes 30$/hour, there&#8217;s no way to detect the problem. There are also other ways to cheat, but they can mostly be detected or prevented by adding complications to the solution. For example, Bob can show Alice the slip he pulled out, to prove he&#8217;s not just lying about the outcome. I don&#8217;t want to dig too deep into the details of what types of cheating you can prevent&#8230; suffice it to say that it goes very deep.</p>
<p>If Bob and Alice were using computers, instead of physical items, they would have used public key cryptography instead of locked suggestions boxes. This makes the computer protocols harder to understand, but removes a lot of corner cases inherent in the physical protocol. It&#8217;s much easier to prevent Alice from secretly marking the slips of paper saying &#8216;no&#8217;, so she can determine which box Bob opened, for example.</p>
<h3>Summary</h3>
<p>You can perform oblivious transfers without computers, using locked suggestions boxes.</p>
<p>The ability to do oblivious transfers is the basis for performing any secure multi-party computation.</p>
<p>&#8212;</p>
<h3>Discuss on <a href="http://www.reddit.com/r/programming/comments/1duqtk/explain_it_like_im_five_the_socialist_millionaire/">Reddit</a>, <a href="https://news.ycombinator.com/item?id=5667275">Hacker News</a></h3>
<p>&#8212;</p>
]]></content:encoded>
			<wfw:commentRss>http://twistedoakstudios.com/blog/Post3724_explain-it-like-im-five-the-socialist-millionaire-problem-and-secure-multi-party-computation/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Computer Science Blows My Mind</title>
		<link>http://twistedoakstudios.com/blog/Post3631_computer-science-blows-my-mind</link>
		<comments>http://twistedoakstudios.com/blog/Post3631_computer-science-blows-my-mind#comments</comments>
		<pubDate>Thu, 02 May 2013 08:27:51 +0000</pubDate>
		<dc:creator>Craig Gidney</dc:creator>
				<category><![CDATA[Academic]]></category>

		<guid isPermaLink="false">http://twistedoakstudios.com/blog/?p=3631</guid>
		<description><![CDATA[Computer science is an interesting discipline. Often, I find myself inadequately trying to communicate why I find it so fascinating. I think I get the closest when describing computer science things that &#8216;blow my mind&#8217;. This post is&#8230; basically just a list of computer science things I think are cool. Physical I remember a time [...]]]></description>
				<content:encoded><![CDATA[<p>Computer science is an interesting discipline. Often, I find myself inadequately trying to communicate why I find it so fascinating. I think I get the closest when describing computer science things that &#8216;blow my mind&#8217;.</p>
<p>This post is&#8230; basically just a list of computer science things I think are cool.</p>
<h3>Physical</h3>
<p>I remember a time when I was very confused about how computers worked. I knew I could type in a program, and the computer would run it, but how that happened was a big mystery. I could write a program to interpret programs, but&#8230; how do I run the interpreter? It can&#8217;t be interpreters all the way down!</p>
<p>When I learned how to make an adder out of logic gates, and realized I could pull the same sort of trick all the way up&#8230; I imagine that&#8217;s how Archimedes felt as he ran through the streets naked after realizing he could measure volume via water displacement.</p>
<p>It sounds a bit silly to say it, but <em>did you know computers run on physics</em>?! Amazing!</p>
<h3>Coloring Complexity</h3>
<p>Suppose you&#8217;re given a map. Your job is to determine if, with a particular number of colors, you can color in all the areas without giving any bordering areas the same color. You don&#8217;t have to actually provide such a coloring, just determine if there is one.</p>
<p>How difficult do you think it is to solve this problem? It actually depends on the number of colors.</p>
<p>With 0 or 1 colors, the problem is trivial. Only graphs without nodes are 0-colorable, and only graphs without edges are 1-colorable.</p>
<p>With 2 colors, the problem is easy. You can solve it in linear time. As soon as you pick the color of one area, you&#8217;re forced to a single possibility for adjacent areas. Just keep filling in areas as you&#8217;re forced to, until you either finish or find a contradiction.</p>
<p>With 3 colors, the <a href="http://webbuild.knu.ac.kr/~mhs/preprints/On%20the%20Complexity%20of%20H-Colouring%20Planar%20Graphs.pdf">problem is very hard</a>. In fact it&#8217;s <a href="http://en.wikipedia.org/wiki/Np-complete">NP-Complete</a>, meaning an algorithm that solves any instance in polynomial time could be repurposed to say&#8230; be the first to find inputs that collide when hashed with <a href="http://en.wikipedia.org/wiki/Sha-1">SHA-1</a>.</p>
<p>With 4 colors, the difficulty changes again. <a href="http://en.wikipedia.org/wiki/Four_color_theorem">Complicated details</a> aside, you can use the following algorithm to solve the problem:</p>
<pre><code class="prettyprint">bool IsFourColorable(PlanarGraph g) {
    return true;
}</code></pre>
<p>Needless to say, planar 4-colorability is a bit easier than planar 3-colorability.</p>
<p>Over-constrained problems are easy, but so are under-constrained problems. Changing tiny details of problems can massively change how easy they are to solve.</p>
<h3>Proofs without Proofs</h3>
<p>Suppose you meet an alien with access to absurd amounts of computational power. The alien is cooperative, but you&#8217;re not sure if it&#8217;s trustworthy. Can the alien help you solve hard computational problems, even though you don&#8217;t trust it and it can probably track everything you do? Can <a href="http://en.wikipedia.org/wiki/Arthur%E2%80%93Merlin_protocol">Arthur extract useful work out of a tricky Merlin</a>?</p>
<p>Welcome to the wonderful world of <a href="http://en.wikipedia.org/wiki/Interactive_proof_system">interactive proofs</a>.</p>
<p>Want to convince me that you have solved a problem or know some information (e.g. a password), without giving me the solution or the information? You can do it with an interactive <a href="http://en.wikipedia.org/wiki/Zero-knowledge_proof">zero knowledge proof</a>. For example, most cryptographic voting systems involve voting machines zero-knowledge-proving that they are functioning correctly at every step.</p>
<p>Want to search through<em>all</em> the different possibilities that could be reached in <em>exponential</em> time, to see if one meets a criteria? All you need is <a href="http://en.wikipedia.org/wiki/Interactive_proof_system#MIP">two isolated provers instead of one</a>. No, seriously, MIP (problems solvable in polynomial time with multiple unbounded interactive provers) is equivalent to <a href="http://en.wikipedia.org/wiki/NEXPTIME">NEXPTIME</a> (problems that can be solved in exponential time, with access to a &#8216;branch both ways&#8217; instruction). This is not quite as practical as zero knowledge proofs, but NEXPTIME is <em>so gigantic</em> that I don&#8217;t care.</p>
<p>In computer science, the idea of a mathematical proof is one special case amongst many strategies to convince verifiers that something is true.</p>
<h3>Secure Multiparty Computation</h3>
<p>A common intuition in real time strategy games is that <a href="http://en.wikipedia.org/wiki/Cheating_in_online_games#Maphacking">map hacks</a> are unavoidable. The game needs to know where enemy units are in order to determine if they can be seen, and a map hack is just a matter of displaying instead of hiding the information&#8230; right? Wrong.</p>
<p><a href="http://en.wikipedia.org/wiki/Secure_multiparty_computation">Secure multiparty computation</a> (SMPC) allows mutually distrusting computers to interact in a way that simulates a trusted server. In the case of an RTS game, the simulated server would compute the answers to questions like &#8220;What units can see each other?&#8221; and then tell the players what they can see. This can be done without any of the players&#8217; computers learning where hidden enemy units are.</p>
<p>Unfortunately, SMPC is quite expensive and requires back-and-forth interaction. It&#8217;s not practical to run it over hundreds of unit positions a hundred times a second. It&#8217;s more applicable to turn based games like civilizations or poker than to real time strategy games.</p>
<p>Still, the fact that having a real trusted third parties is unnecessary (it&#8217;s more like&#8230; an optimization) is very cool.</p>
<h3>Halt</h3>
<p>You&#8217;ve probably head of the <a href="http://en.wikipedia.org/wiki/Halting_problem">halting problem</a>. Basically, it&#8217;s a more concrete version of Gödel&#8217;s incompleteness theorem: instead of proving xor disproving every statement, you want to find a program that determines if given programs halt.</p>
<p>It is the case that no program solves the halting problem. This is quite possibly the most actively counter-intuitive thing I know.</p>
<p>For example, you can write a (partial) halting solver that works by enumerating all mathematical proofs until a proof that the program in question halts is found or a proof that the program in question doesn&#8217;t halt is found. The only way such a solver can fail is if there are &#8220;unfathomable&#8221; programs that run forever, with no possible proof <em>even in principle</em> that they run forever. (Alternatively: you used an inconsistent proof system.)</p>
<p>Unfathomable programs exist.</p>
<p>The idea of unfathomable programs breaks my brain. Again and again, I end up with the same confused questions: if there&#8217;s no proof the machine doesn&#8217;t halt, in what sense does the fact that it doesn&#8217;t halt even exist? How does it make any sense to require an infinitely large proof about any aspect of a machine with a finite-sized specification?</p>
<p>Even worse, unfathomable programs are impossible to find. Confirming you had a no-proof-but-runs-forever program would involve proving it ran forever and then proving you didn&#8217;t just prove that last thing.</p>
<p>Basically, the halting problem can be used to produce the feeling of confusion-about-<em>reality-itself</em> on demand. It&#8217;s just that mind blowing to me.</p>
<h3>Summary</h3>
<p>Computer science interesting. Craig like.</p>
<p>&#8212;</p>
<h3>Discuss on <a href="http://www.reddit.com/r/programming/comments/1djh83/computer_science_blows_my_mind/?already_submitted=true">Reddit</a></h3>
<p>&#8212;</p>
]]></content:encoded>
			<wfw:commentRss>http://twistedoakstudios.com/blog/Post3631_computer-science-blows-my-mind/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A visit to Execution Labs in Montréal</title>
		<link>http://twistedoakstudios.com/blog/Post3484_a-visit-to-execution-labs-in-montreal</link>
		<comments>http://twistedoakstudios.com/blog/Post3484_a-visit-to-execution-labs-in-montreal#comments</comments>
		<pubDate>Mon, 29 Apr 2013 20:18:22 +0000</pubDate>
		<dc:creator>horsman</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://twistedoakstudios.com/blog/?p=3484</guid>
		<description><![CDATA[On the way home from Game Developer&#8217;s Conference this year I went to Montréal to spend a week as a mentor in Execution Labs, Jason Della Rocca&#8216;s indie incubator. The space is situated on the plateau near the infamous Schwartz&#8217;s Deli. On Tuesday the day began with a prepared presentation &#8216;Lenses: A comfortable way to [...]]]></description>
				<content:encoded><![CDATA[<p>On the way home from Game Developer&#8217;s Conference this year I went to Montréal to spend a week as a mentor in <a href="http://executionlabs.com/" title="Execution Labs">Execution Labs</a>,  <a href="http://en.wikipedia.org/wiki/Jason_Della_Rocca" title="Jason Della Rocca">Jason Della Rocca</a>&#8216;s indie incubator. The space is situated on the plateau near the infamous <a href="http://en.wikipedia.org/wiki/Schwartz%27s">Schwartz&#8217;s Deli</a>.</p>
<p>On Tuesday the day began with a prepared presentation &#8216;Lenses: A comfortable way to manage shared state&#8217;. It covered in depth a thought that Craig touched on in <a href="http://twistedoakstudios.com/blog/Post1823_decoupling-shared-control" title="Decoupling Shared Control">a previous blog post</a>. Slides are available <a href="https://docs.google.com/presentation/d/1MQfjDcVOCqSQ0RLyEbQKLhAG2sI44wjrKElM3FZbvF8/edit?usp=sharing" title="Lenses Slides">here</a> and generic implementation + sample code is <a href="https://github.com/TwistedOakStudios/TOUnityUtilities/tree/master/Assets/Lenses" title="Lenses code @ Git Hub">here</a>. </p>
<p>After the talk I was able to meet each of the impressive teams working on great mobile games. I was especially impressed with Double Stallion&#8217;s <a href="http://doublestalliongames.com/" title="Big Action Mega Fight!">Big Action Mega Fight</a> (BAMF for short; Hmmmm&#8230;) on the technical side of things. I enjoyed excellent design conversation with <a href="http://www.lightningrodgames.com/" title="Lightning Rod Games Website">Lightning Rod Games&#8217;</a> Steven Smith and <a href="https://www.facebook.com/imaginarygames" title="Imaginary Games">Imaginary Games</a>&#8216; Chris Powell; both multi-talented developer/designer/bizdudes. Andrew at Miscellaneum Studios and I talked at length about cross platform GUI, Continuous Integration and <a href="http://docs.unity3d.com/Documentation/Manual/ExecutionOrder.html" title="Unity Manual: Execution Order of Scripts">Unity&#8217;s Script Execution Order</a> for the camera in their title <a href="http://thefiremasters.tumblr.com/" title="The Firemasters Website">The Firemasters</a>. Finally I was able to play through Pixel Crucible&#8217;s work in progress game which is <a href="http://pixelcrucible.com/2013/04/standing-on-the-shoulders-of-giants-part-one/" title="Pixel Crucible Blog">draws inspiration</a> from some of my favorite games.</p>
<p>Next up was <a href="http://mrgs.ca/forum/index.php/topic,83.0.html" title="Recap Post">Mont Royal Game Society monthly meetup</a> where I tried my hand at Super Punch ball and had entirely too much poutine. Then on Thursday was a 5 á 7 with <a href="http://tag.hexagram.ca/" title="TAG Concordia">TAG Concordia</a> where I learned how to play <a href="http://tag.hexagram.ca/events/april-4-5a7-symposium-japanese-theme-night/" title="5 a 7">koi koi</a> with otakus and game designers.</p>
<p>Friday capped off my journey with a wonderful visit to <a href="http://www.weareminority.com/en/" title="Minority Media">Minority Media</a> followed by giving a talk to the <a href="http://www.meetup.com/MontrealUnityGames/" title="Montreal Unity User Group">Montreal Unity User Group</a> where I demoed my (potential) talk for Unite 2013 on extending coroutines (Based on <a href="http://twistedoakstudios.com/blog/Post83_coroutines-more-than-you-want-to-know" title="Coroutines">this post</a> but made a bit more accessible). After the talk I went to a really great japanese whiskey bar on St. Laurent. and crashed with some awesome game designers.</p>
<p>Montreal is one hell of a game development scene that I would be proud to call home; but boy was I ready to be back in Halifax after the 2.5 week tour-de-force. Next stop, Toronto for <a href="http://www.tojam.ca/home/default.asp" title="TOJAM8">TOJAM8</a> with Petar and Paul and a MIDI controller!</p>
]]></content:encoded>
			<wfw:commentRss>http://twistedoakstudios.com/blog/Post3484_a-visit-to-execution-labs-in-montreal/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Transmuting Dice, Conserving Entropy</title>
		<link>http://twistedoakstudios.com/blog/Post3573_transmuting-dice-conserving-entropy</link>
		<comments>http://twistedoakstudios.com/blog/Post3573_transmuting-dice-conserving-entropy#comments</comments>
		<pubDate>Tue, 23 Apr 2013 07:21:03 +0000</pubDate>
		<dc:creator>Craig Gidney</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Entropy]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Puzzle]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[computer science]]></category>
		<category><![CDATA[entropy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[puzzle]]></category>

		<guid isPermaLink="false">http://twistedoakstudios.com/blog/?p=3573</guid>
		<description><![CDATA[Suppose you want to play a game of backgammon. Unfortunately, horror of horrors, you have lots of pocket change but no dice! You realize you can generate random values by flipping coins, but a coin flip has two possible outcomes instead of six. How do you simulate a fair six sided die using only fair [...]]]></description>
				<content:encoded><![CDATA[<p>Suppose you want to play a game of backgammon. Unfortunately, horror of horrors, you have lots of pocket change but no dice!</p>
<p>You realize you can generate random values by flipping coins, but a coin flip has two possible outcomes instead of six. How do you simulate a <em>fair</em> six sided die using only fair coin flips? What about the more general problem, of simulating an <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-daca0f1fa28cfa1c4b587dbe62de2ad6_l3.png" class="ql-img-inline-formula " alt="&#109;" title="Rendered by QuickLaTeX.com" height="8" width="15" style="vertical-align: 0px;"/>-sided die with an <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-edffd8b3cef05b01503b30332a649a06_l3.png" class="ql-img-inline-formula " alt="&#110;" title="Rendered by QuickLaTeX.com" height="8" width="11" style="vertical-align: 0px;"/>-sided die?</p>
<p><em>If you haven&#8217;t seen this puzzle before today, and want to solve it yourself, stop now. I will be spoiling it.</em></p>
<h3>Partial Credit</h3>
<p>There&#8217;s a well known sub-optimal solution to this problem.</p>
<p>First, given a die with <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-edffd8b3cef05b01503b30332a649a06_l3.png" class="ql-img-inline-formula " alt="&#110;" title="Rendered by QuickLaTeX.com" height="8" width="11" style="vertical-align: 0px;"/> sides, it&#8217;s trivial to simulate a die with <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-2c308b58e94ddb207e2aa477eabd8395_l3.png" class="ql-img-inline-formula " alt="&#110;&#94;&#112;" title="Rendered by QuickLaTeX.com" height="12" width="18" style="vertical-align: 0px;"/> sides by grouping rolls. A <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-2f3540997c670fd51fe9f7f76a01e6e3_l3.png" class="ql-img-inline-formula " alt="&#50;&#94;&#51;&#32;&#61;&#32;&#56;" title="Rendered by QuickLaTeX.com" height="15" width="49" style="vertical-align: 0px;"/> sided die can be simulated by arranging coin flips into groups of <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f67e4359381fb1dc4065ce3995f50ff3_l3.png" class="ql-img-inline-formula " alt="&#51;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>, because each group has <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-7ce5156d73d30e294c4237b9a3b0d324_l3.png" class="ql-img-inline-formula " alt="&#56;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/> equally likely possibilities. The reverse direction, from <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-2c308b58e94ddb207e2aa477eabd8395_l3.png" class="ql-img-inline-formula " alt="&#110;&#94;&#112;" title="Rendered by QuickLaTeX.com" height="12" width="18" style="vertical-align: 0px;"/> to <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-edffd8b3cef05b01503b30332a649a06_l3.png" class="ql-img-inline-formula " alt="&#110;" title="Rendered by QuickLaTeX.com" height="8" width="11" style="vertical-align: 0px;"/>, is also easy because each roll can be split evenly into <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-1448e0dd792bfdb9af2577d22840240a_l3.png" class="ql-img-inline-formula " alt="&#112;" title="Rendered by QuickLaTeX.com" height="12" width="10" style="vertical-align: -4px;"/> sub-rolls.</p>
<p>Second, given a die with more sides than necessary, you can just filter out rolls that have invalid results with respect to the smaller die. Given an <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-7ce5156d73d30e294c4237b9a3b0d324_l3.png" class="ql-img-inline-formula " alt="&#56;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>-sided die, we can simulate a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-2d98f765095fb5e6ae1e038e55ebe38e_l3.png" class="ql-img-inline-formula " alt="&#54;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/> sided die by rolling until we <a href="http://en.wikipedia.org/wiki/Almost_certain">almost surely</a> get a result that&#8217;s not <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-506cb52691b232e59de7782421fde5f7_l3.png" class="ql-img-inline-formula " alt="&#55;" title="Rendered by QuickLaTeX.com" height="13" width="9" style="vertical-align: 0px;"/> or <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-7ce5156d73d30e294c4237b9a3b0d324_l3.png" class="ql-img-inline-formula " alt="&#56;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>.</p>
<p>Putting these two parts together allows us to simulate a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-2d98f765095fb5e6ae1e038e55ebe38e_l3.png" class="ql-img-inline-formula " alt="&#54;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>-sided die using only our <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-5b41363ecafa32246737add70da4a65a_l3.png" class="ql-img-inline-formula " alt="&#50;" title="Rendered by QuickLaTeX.com" height="12" width="8" style="vertical-align: 0px;"/>-sided coin. Just flip the coin three times, pairing each of the <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-7ce5156d73d30e294c4237b9a3b0d324_l3.png" class="ql-img-inline-formula " alt="&#56;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/> possible outcomes with the numbers <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-99ef48eeaa52afd5965a742f9aed12cd_l3.png" class="ql-img-inline-formula " alt="&#49;" title="Rendered by QuickLaTeX.com" height="13" width="7" style="vertical-align: -1px;"/> to <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-7ce5156d73d30e294c4237b9a3b0d324_l3.png" class="ql-img-inline-formula " alt="&#56;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>, and try again whenever the result is <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-506cb52691b232e59de7782421fde5f7_l3.png" class="ql-img-inline-formula " alt="&#55;" title="Rendered by QuickLaTeX.com" height="13" width="9" style="vertical-align: 0px;"/> or <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-7ce5156d73d30e294c4237b9a3b0d324_l3.png" class="ql-img-inline-formula " alt="&#56;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>.</p>
<p>There. Solved. Well&#8230; except it feels wasteful to throw away those sevens and eights.</p>
<h3>Wasted Entropy</h3>
<p>The above solution wastes <a href="http://en.wikipedia.org/wiki/Information_entropy">information entropy</a>. A coin flip generates 1 bit of entropy. Three coin flips generates 3 bits of entropy. The result of the roll of a six sided die, on the other hand, gives you only <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-5380eb9c4a874ea1283a7d75ca5c2ddd_l3.png" class="ql-img-inline-formula " alt="&#108;&#111;&#103;&#95;&#50;&#32;&#54;&#32;&#92;&#97;&#112;&#112;&#114;&#111;&#120;&#32;&#50;&#46;&#54;" title="Rendered by QuickLaTeX.com" height="17" width="86" style="vertical-align: -4px;"/> bits of entropy.</p>
<p>Even if we get lucky, and don&#8217;t have to try again, we&#8217;re consuming <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f67e4359381fb1dc4065ce3995f50ff3_l3.png" class="ql-img-inline-formula " alt="&#51;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/> bits of entropy while only producing <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-c687fbb9a0ff6e7fd0439e3dbf6e9fd5_l3.png" class="ql-img-inline-formula " alt="&#50;&#46;&#54;" title="Rendered by QuickLaTeX.com" height="12" width="23" style="vertical-align: 0px;"/> bits when converting our coin flips into six sided die rolls. If we&#8217;re average, instead of lucky, then we&#8217;ll need an expected <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-76f1c745c05f6588db1ecdd229fbfd85_l3.png" class="ql-img-inline-formula " alt="&#92;&#102;&#114;&#97;&#99;&#123;&#56;&#125;&#123;&#54;&#125;" title="Rendered by QuickLaTeX.com" height="22" width="7" style="vertical-align: -6px;"/> attempts for an expected cost of <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-50b31d5d39cbeddfcefcfb149cc6ec29_l3.png" class="ql-img-inline-formula " alt="&#92;&#102;&#114;&#97;&#99;&#123;&#56;&#125;&#123;&#54;&#125;&#32;&#92;&#99;&#100;&#111;&#116;&#32;&#51;&#32;&#61;&#32;&#52;" title="Rendered by QuickLaTeX.com" height="22" width="63" style="vertical-align: -6px;"/> bits. We&#8217;re wasting <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-2082940e0f8071a88350ae5166c209f6_l3.png" class="ql-img-inline-formula " alt="&#49;&#46;&#52;" title="Rendered by QuickLaTeX.com" height="13" width="22" style="vertical-align: -1px;"/> bits of precious, delicious entropy per generated roll!</p>
<p>This raises the question: can we do better? Can we use that wasted entropy?</p>
<p><em>This is your second chance to stop and solve.</em></p>
<h3>Entropy Optimizations</h3>
<p>There are several optimizations that we can make, to improve our entropy efficiency.</p>
<p>For example, consider what happens if we map [heads,heads,heads] to <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-506cb52691b232e59de7782421fde5f7_l3.png" class="ql-img-inline-formula " alt="&#55;" title="Rendered by QuickLaTeX.com" height="13" width="9" style="vertical-align: 0px;"/> and [heads,heads,tails] to <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-7ce5156d73d30e294c4237b9a3b0d324_l3.png" class="ql-img-inline-formula " alt="&#56;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>. Since they both start with [heads, heads], the third coin flip has no effect on whether or not we retry. This allows us to save one coin flip when retrying, reducing our expected cost from <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-ee307041d6be6db99ad351a24247695f_l3.png" class="ql-img-inline-formula " alt="&#52;" title="Rendered by QuickLaTeX.com" height="13" width="9" style="vertical-align: -1px;"/> to <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-e73f29e3fb279c439be42e9dff3abc75_l3.png" class="ql-img-inline-formula " alt="&#51;&#32;&#43;&#32;&#40;&#92;&#102;&#114;&#97;&#99;&#123;&#56;&#125;&#123;&#54;&#125;&#45;&#49;&#41;&#32;&#92;&#99;&#100;&#111;&#116;&#32;&#50;&#32;&#61;&#32;&#51;&#46;&#54;&#54;&#54;&#46;&#46;&#46;" title="Rendered by QuickLaTeX.com" height="22" width="186" style="vertical-align: -6px;"/> bits.</p>
<p>Another useful optimization to notice is that <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-2d98f765095fb5e6ae1e038e55ebe38e_l3.png" class="ql-img-inline-formula " alt="&#54;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/> factors into <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-5b41363ecafa32246737add70da4a65a_l3.png" class="ql-img-inline-formula " alt="&#50;" title="Rendered by QuickLaTeX.com" height="12" width="8" style="vertical-align: 0px;"/> and <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f67e4359381fb1dc4065ce3995f50ff3_l3.png" class="ql-img-inline-formula " alt="&#51;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>, and that the product of two uniformly random numbers is also uniformly random. A <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-2d98f765095fb5e6ae1e038e55ebe38e_l3.png" class="ql-img-inline-formula " alt="&#54;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>-sided die roll is interchangeable with a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-5b41363ecafa32246737add70da4a65a_l3.png" class="ql-img-inline-formula " alt="&#50;" title="Rendered by QuickLaTeX.com" height="12" width="8" style="vertical-align: 0px;"/>-sided die roll combined with a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f67e4359381fb1dc4065ce3995f50ff3_l3.png" class="ql-img-inline-formula " alt="&#51;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>-sided die roll. Since we have a coin with <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-5b41363ecafa32246737add70da4a65a_l3.png" class="ql-img-inline-formula " alt="&#50;" title="Rendered by QuickLaTeX.com" height="12" width="8" style="vertical-align: 0px;"/> sides, <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-5b41363ecafa32246737add70da4a65a_l3.png" class="ql-img-inline-formula " alt="&#50;" title="Rendered by QuickLaTeX.com" height="12" width="8" style="vertical-align: 0px;"/>-sided die rolls are trivial to do with perfect efficiency. Then, for each <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-5b41363ecafa32246737add70da4a65a_l3.png" class="ql-img-inline-formula " alt="&#50;" title="Rendered by QuickLaTeX.com" height="12" width="8" style="vertical-align: 0px;"/>-sided roll we generate, we can generate an accompanying <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f67e4359381fb1dc4065ce3995f50ff3_l3.png" class="ql-img-inline-formula " alt="&#51;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>-sided roll by using groups of <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-5b41363ecafa32246737add70da4a65a_l3.png" class="ql-img-inline-formula " alt="&#50;" title="Rendered by QuickLaTeX.com" height="12" width="8" style="vertical-align: 0px;"/> coin flips (and retrying when we get a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-ee307041d6be6db99ad351a24247695f_l3.png" class="ql-img-inline-formula " alt="&#52;" title="Rendered by QuickLaTeX.com" height="13" width="9" style="vertical-align: -1px;"/> instead of <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-99ef48eeaa52afd5965a742f9aed12cd_l3.png" class="ql-img-inline-formula " alt="&#49;" title="Rendered by QuickLaTeX.com" height="13" width="7" style="vertical-align: -1px;"/>, <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-5b41363ecafa32246737add70da4a65a_l3.png" class="ql-img-inline-formula " alt="&#50;" title="Rendered by QuickLaTeX.com" height="12" width="8" style="vertical-align: 0px;"/>, or <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f67e4359381fb1dc4065ce3995f50ff3_l3.png" class="ql-img-inline-formula " alt="&#51;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>). Combined with the previous optimization, this lowers our cost to <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-aed4a2960e122a88e6a1a856bc1fd197_l3.png" class="ql-img-inline-formula " alt="&#49;&#32;&#43;&#32;&#50;&#32;&#43;&#32;&#40;&#92;&#102;&#114;&#97;&#99;&#123;&#52;&#125;&#123;&#51;&#125;&#45;&#49;&#41;&#92;&#99;&#100;&#111;&#116;&#32;&#49;&#32;&#61;&#32;&#51;&#46;&#51;&#51;&#51;&#46;&#46;&#46;" title="Rendered by QuickLaTeX.com" height="22" width="215" style="vertical-align: -6px;"/> bits.</p>
<p>A more flexible optimization is to find a power of <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-5b41363ecafa32246737add70da4a65a_l3.png" class="ql-img-inline-formula " alt="&#50;" title="Rendered by QuickLaTeX.com" height="12" width="8" style="vertical-align: 0px;"/> that comes proportionally sooner after a power of <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f67e4359381fb1dc4065ce3995f50ff3_l3.png" class="ql-img-inline-formula " alt="&#51;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>. For example, we can use our coin to simulate rolling a die with <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-a14c90702c502048d74ff7c5a23ee55a_l3.png" class="ql-img-inline-formula " alt="&#50;&#94;&#53;&#61;&#51;&#50;" title="Rendered by QuickLaTeX.com" height="15" width="57" style="vertical-align: 0px;"/> sides with perfect efficiency, discard when we exceed <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f2d90b34a01fbffcdaed56946321ba03_l3.png" class="ql-img-inline-formula " alt="&#51;&#94;&#51;&#61;&#50;&#55;" title="Rendered by QuickLaTeX.com" height="15" width="58" style="vertical-align: 0px;"/>, and generate three rolls of a <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f67e4359381fb1dc4065ce3995f50ff3_l3.png" class="ql-img-inline-formula " alt="&#51;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>-sided die per success. It takes more coin flips to get our first result, but the probability of discarding decreases significantly. Combined with our previous two optimizations, we&#8217;ve lowered our expected cost to <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-339dd6c2384a47a60accde47e2d8f094_l3.png" class="ql-img-inline-formula " alt="&#92;&#102;&#114;&#97;&#99;&#123;&#49;&#125;&#123;&#51;&#125;&#40;&#51;&#32;&#43;&#32;&#53;&#32;&#43;&#32;&#40;&#92;&#102;&#114;&#97;&#99;&#123;&#51;&#50;&#125;&#123;&#50;&#55;&#125;&#45;&#49;&#41;&#32;&#92;&#99;&#100;&#111;&#116;&#32;&#51;&#41;&#32;&#61;&#32;&#50;&#46;&#56;&#53;&#49;&#56;&#53;&#49;&#46;&#46;&#46;" title="Rendered by QuickLaTeX.com" height="22" width="273" style="vertical-align: -6px;"/> bits.</p>
<p>We can find even better powers of <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-5b41363ecafa32246737add70da4a65a_l3.png" class="ql-img-inline-formula " alt="&#50;" title="Rendered by QuickLaTeX.com" height="12" width="8" style="vertical-align: 0px;"/> and <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-f67e4359381fb1dc4065ce3995f50ff3_l3.png" class="ql-img-inline-formula " alt="&#51;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/>. The next few good powers are <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-991f95d9b16f602f77d64795d53aa251_l3.png" class="ql-img-inline-formula " alt="&#40;&#51;&#94;&#53;&#44;&#50;&#94;&#56;&#41;" title="Rendered by QuickLaTeX.com" height="19" width="53" style="vertical-align: -4px;"/>, <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-fe1b414ca5451e2a2111b466dd44ba12_l3.png" class="ql-img-inline-formula " alt="&#40;&#51;&#94;&#123;&#49;&#55;&#125;&#44;&#50;&#94;&#123;&#50;&#55;&#125;&#41;" title="Rendered by QuickLaTeX.com" height="19" width="67" style="vertical-align: -4px;"/> and <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-082c272e9c3c6b37573e75394280297a_l3.png" class="ql-img-inline-formula " alt="&#40;&#51;&#94;&#123;&#51;&#57;&#125;&#44;&#50;&#94;&#123;&#52;&#54;&#125;&#41;" title="Rendered by QuickLaTeX.com" height="19" width="67" style="vertical-align: -4px;"/>. Each gets us tantalizingly closer to perfect efficiency, and it&#8217;s not even that hard to find good pairs. Just run the following program for sufficiently long:</p>
<pre><code class="prettyprint">BigRational r = 3;
int n2 = 0;
int n3 = 1;
BigRational best = 0;
while (true) {
    while (r > 1) {
        r /= 2;
        n2 += 1;
    }
    if (r > best) {
        best = r;
        Console.WriteLine("3^{0},2^{1}", n3, n2);
    }
    while (r < 1) {
        r *= 3;
        n3 += 1;
    }
}</code></pre>
<p>(Note that the BigRational type is not standard. I referenced it from the <a href="https://nuget.org/packages/BigRationalLibrary/">BigRationalLibrary NuGet package</a>.)</p>
<p>Now for some disappointing news: you'll never find the perfect pair of powers. We can achieve <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-5dc9e05ac40dac3d571b8e2e5a0e3de0_l3.png" class="ql-img-inline-formula " alt="&#126;&#57;&#57;&#46;&#57;&#57;&#56;" title="Rendered by QuickLaTeX.com" height="12" width="50" style="vertical-align: 0px;"/>% efficiency with <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-e02f9bf126fc6384b4d1c49232e44b6d_l3.png" class="ql-img-inline-formula " alt="&#51;&#94;&#123;&#49;&#53;&#54;&#48;&#49;&#125;" title="Rendered by QuickLaTeX.com" height="15" width="43" style="vertical-align: 0px;"/> and <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-c6bdffc7d0b80949462b633d475669a6_l3.png" class="ql-img-inline-formula " alt="&#50;&#94;&#123;&#50;&#52;&#55;&#50;&#55;&#125;" title="Rendered by QuickLaTeX.com" height="15" width="44" style="vertical-align: 0px;"/>. We can achieve <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-3f83579ba7aae8392ef77dead583be1b_l3.png" class="ql-img-inline-formula " alt="&#126;&#57;&#57;&#46;&#57;&#57;&#57;" title="Rendered by QuickLaTeX.com" height="12" width="50" style="vertical-align: 0px;"/>% efficiency with <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-eb8c12f3b3009ab0fd43448858e76dd9_l3.png" class="ql-img-inline-formula " alt="&#51;&#94;&#123;&#52;&#55;&#52;&#54;&#56;&#125;" title="Rendered by QuickLaTeX.com" height="15" width="44" style="vertical-align: 0px;"/> and <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-6e8ac65a238bd16409bb426c4c618886_l3.png" class="ql-img-inline-formula " alt="&#50;&#94;&#123;&#55;&#53;&#50;&#51;&#53;&#125;" title="Rendered by QuickLaTeX.com" height="15" width="44" style="vertical-align: 0px;"/>. We can get arbitrarily close, but we can't achieve <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-c985b26df69bd12fbee7783e59bee7b0_l3.png" class="ql-img-inline-formula " alt="&#49;&#48;&#48;" title="Rendered by QuickLaTeX.com" height="13" width="26" style="vertical-align: -1px;"/>% efficiency. Doing so would require an impossibility: a power of three that's also a power of two. That's not going to happen. Powers of three aren't even ever even! No matter how big we make the constants, there will always be some unlikely cases where we have to discard and try again.</p>
<p>Give that achieving <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-c985b26df69bd12fbee7783e59bee7b0_l3.png" class="ql-img-inline-formula " alt="&#49;&#48;&#48;" title="Rendered by QuickLaTeX.com" height="13" width="26" style="vertical-align: -1px;"/>% efficiency is impossible, and given that we can get arbitrarily close to <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-c985b26df69bd12fbee7783e59bee7b0_l3.png" class="ql-img-inline-formula " alt="&#49;&#48;&#48;" title="Rendered by QuickLaTeX.com" height="13" width="26" style="vertical-align: -1px;"/>% by choosing the right constants, a person would be tempted to think we'd hit the limit. That we can't do any better. That person would be wrong.</p>
<p><em>Last chance to solve on your own.</em></p>
<h3>Conservation of Entropy</h3>
<p>Beating 'choose how close you want to be to 100% efficiency' is just a matter of not settling for a fixed amount of efficiency. One way to do this would be to compute better constants as we generated die rolls. As the algorithm ran longer and longer, it would waste less and less entropy.</p>
<p>However, it turns out we can do something slightly simpler: <a href="http://en.wikipedia.org/wiki/Arithmetic_coding">arithmetic coding</a>. The idea is to treat the coin flips as the binary digits after the decimal point (binary point?) of a number between <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-83cddce8856ba73347de5d27a0833036_l3.png" class="ql-img-inline-formula " alt="&#48;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/> and <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-99ef48eeaa52afd5965a742f9aed12cd_l3.png" class="ql-img-inline-formula " alt="&#49;" title="Rendered by QuickLaTeX.com" height="13" width="7" style="vertical-align: -1px;"/>. As we add more binary digits, the space where the 'complete' number can lie becomes smaller and smaller. Eventually, that space will almost certainly fall entirely within the domain covered by a single digit in base 6. We can then safely output that digit, and start waiting for the next base 6 digit to become fixed.</p>
<p>This idea easily generalizes to dies with arbitrary numbers of sides. The following code implements it:</p>
<pre><code class="prettyprint">///&lt;summary&gt;Generates rolls of a uniformly random die, based on rolls of a uniformly random die with a different number of sides.&lt;/summary&gt;
public static IEnumerable&lt;int&gt; ChangeDiceSideCountFromTo(this IEnumerable&lt;int&gt; rollResults, 
                                                         int oldSideCount, 
                                                         int newSideCount) {
    if (rollResults == null) throw new ArgumentNullException("rollResults");
    if (oldSideCount &lt; 2) throw new ArgumentOutOfRangeException("oldSideCount", "oldSideCount &lt; 2");
    if (newSideCount &lt; 2) throw new ArgumentOutOfRangeException("newSideCount", "newSideCount &lt; 2");

    BigRational min = 0;
    BigRational len = 1;
    foreach (var roll in rollResults) {
        // the roll represents the next digit in base-[number of old sides], reducing the valid range
        len /= oldSideCount;
        min += roll * len;

        // check for digits in base-[number of new sides] becoming fixed
        while (true) {
            var minDigit = (min * newSideCount).GetWholePart();
            var maxExclusive = (min + len) * newSideCount;
            var epsilon = new BigRational(-1, maxExclusive.Denominator * newSideCount);
            var maxDigit = (maxExclusive - epsilon).GetWholePart();
            if (minDigit != maxDigit) break;

            // another digit has become fixed and can be output
            yield return (int)minDigit;

            // normalize so the range of the next digit also ranges from 0 to 1
            len *= newSideCount;
            min *= newSideCount;
            min -= minDigit;
        }
    }        
}</code></pre>
<p>The above code achieves 100% efficiency, with a small caveat: delay. If you convert from an <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-edffd8b3cef05b01503b30332a649a06_l3.png" class="ql-img-inline-formula " alt="&#110;" title="Rendered by QuickLaTeX.com" height="8" width="11" style="vertical-align: 0px;"/> sided die to an <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-daca0f1fa28cfa1c4b587dbe62de2ad6_l3.png" class="ql-img-inline-formula " alt="&#109;" title="Rendered by QuickLaTeX.com" height="8" width="15" style="vertical-align: 0px;"/> sided die and then <em>back</em> to an <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-edffd8b3cef05b01503b30332a649a06_l3.png" class="ql-img-inline-formula " alt="&#110;" title="Rendered by QuickLaTeX.com" height="8" width="11" style="vertical-align: 0px;"/> sided die, you'll get the exact same rolls out that you put in. That proves no entropy is lost. However, the output rolls will lag the input rolls by an expected constant amount. This delay occurs because different bases have different borders between digits.</p>
<p>For example, binary numbers starting with 0.1010101010 may start with 0.1 or 0.2 when represented in ternary. Until you almost certainly roll outside of the repeating 101010 pattern, the next ternary digit can't be determined. On the bright side, when you do finally roll outside of a repeating pattern that delays results, you get a large number of results all at once.</p>
<p>When converting from <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-5b41363ecafa32246737add70da4a65a_l3.png" class="ql-img-inline-formula " alt="&#50;" title="Rendered by QuickLaTeX.com" height="12" width="8" style="vertical-align: 0px;"/> sides to <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-2d98f765095fb5e6ae1e038e55ebe38e_l3.png" class="ql-img-inline-formula " alt="&#54;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/> sides and back, I measured average delays between <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-66d98b91d71572d3ccd1053ac8d41c96_l3.png" class="ql-img-inline-formula " alt="&#52;&#46;&#53;" title="Rendered by QuickLaTeX.com" height="14" width="22" style="vertical-align: -1px;"/> and <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-71b47fdaedf50efe0b81a893406358d9_l3.png" class="ql-img-inline-formula " alt="&#52;&#46;&#57;" title="Rendered by QuickLaTeX.com" height="13" width="23" style="vertical-align: -1px;"/> flips. The effect of the delay on our percentage of efficiency limits to <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-83cddce8856ba73347de5d27a0833036_l3.png" class="ql-img-inline-formula " alt="&#48;" title="Rendered by QuickLaTeX.com" height="12" width="9" style="vertical-align: 0px;"/> as the number of rolls increases.</p>
<p>This is as far as we can go, I think. We never lose any rolls, so entropy is never permanently lost, but there's a small delay. Oh, and the performance is awful. The rational numbers used in the computation don't stay small (unless one of the dice has a number of sides that divides the other die's number of sides). They get bigger and bigger and BIGGER as you generate more rolls. It doesn't take long to convert a thousand rolls, but ten thousand is going to take a minute. Literally.</p>
<h3>Summary</h3>
<p>You can convert an <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-edffd8b3cef05b01503b30332a649a06_l3.png" class="ql-img-inline-formula " alt="&#110;" title="Rendered by QuickLaTeX.com" height="8" width="11" style="vertical-align: 0px;"/>-sided die to an <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-daca0f1fa28cfa1c4b587dbe62de2ad6_l3.png" class="ql-img-inline-formula " alt="&#109;" title="Rendered by QuickLaTeX.com" height="8" width="15" style="vertical-align: 0px;"/>-sided die without losing any entropy, with the caveat that you expect a constant small delay between having generated enough entropy and yielding the next roll.</p>
<p>This solution is interesting theoretically, but note that in practice you'd be far better off doing naive discarding (the constants <img src="http://twistedoakstudios.com/blog/wp-content/ql-cache/quicklatex.com-d478d47e16ab7643af6e52b4fc79d6bf_l3.png" class="ql-img-inline-formula " alt="&#51;&#94;&#123;&#49;&#55;&#125;&#44;&#50;&#94;&#123;&#50;&#55;&#125;" title="Rendered by QuickLaTeX.com" height="19" width="54" style="vertical-align: -4px;"/> work well for coins-to-dice). Entropy is not particularly expensive. You can afford to waste 4% of it.</p>
<p>---</p>
<h3>Discuss on <a href="http://www.reddit.com/r/programming/comments/1cx8nl/transmuting_dice_conserving_entropy/">Reddit</a>, <a href="https://news.ycombinator.com/item?id=5593750">Hacker News</a></h3>
<p>---</p>
]]></content:encoded>
			<wfw:commentRss>http://twistedoakstudios.com/blog/Post3573_transmuting-dice-conserving-entropy/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
