<?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>techtangents</title>
	<atom:link href="http://www.techtangents.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.techtangents.com</link>
	<description></description>
	<lastBuildDate>Wed, 25 Jan 2012 14:54:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>CUPS printer server on Freebsd</title>
		<link>http://www.techtangents.com/cups-printer-server-on-freebsd/</link>
		<comments>http://www.techtangents.com/cups-printer-server-on-freebsd/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 14:54:03 +0000</pubDate>
		<dc:creator>techtangents</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.techtangents.com/?p=457</guid>
		<description><![CDATA[Mainly for my own reference. This is how I did it: Install Avahi (was already installed for netatalk/afp) Install CUPS per http://www.freebsd.org/doc/en/articles/cups/index.html Installed without Avahi support, due to some known bug. This prevents CUPS telling Avahi about the printer and requires the service file below. Magic sprinkles in /usr/local/etc/cups/cupsd.conf: Add an appropriate &#8220;allow&#8221; statement to [...]]]></description>
			<content:encoded><![CDATA[<p>Mainly for my own reference. This is how I did it:</p>
<ol>
<li>Install Avahi (was already installed for netatalk/afp)</li>
<li>Install CUPS per http://www.freebsd.org/doc/en/articles/cups/index.html</li>
<ol>
<li>Installed without Avahi support, due to some known bug. This prevents CUPS telling Avahi about the printer and requires the service file below.</li>
</ol>
<li>Magic sprinkles in /usr/local/etc/cups/cupsd.conf:</li>
<ol>
<li>Add an appropriate &#8220;allow&#8221; statement to the &lt;Location /&gt;, otherwise it denies access</li>
<li>ServerAlias *</li>
</ol>
<li>Downloaded printer driver file from http://www.openprinting.org/printers</li>
<li>Set up printer via cups weberface.</li>
<li>Tweaked and saved config via cups weberface &#8211; note this blats the config so check settings manually</li>
<li>The avahi settings file template from http://wiki.zs64.net/FreeBSD,_CUPS_and_iPad_printing</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.techtangents.com/cups-printer-server-on-freebsd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The &#8220;Maybe Cake&#8221; puzzle</title>
		<link>http://www.techtangents.com/the-maybe-cake-puzzle/</link>
		<comments>http://www.techtangents.com/the-maybe-cake-puzzle/#comments</comments>
		<pubDate>Tue, 25 Oct 2011 12:26:55 +0000</pubDate>
		<dc:creator>techtangents</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.techtangents.com/?p=454</guid>
		<description><![CDATA[Here&#8217;s a programming puzzle I created, which deals with a bunch of dependent pieces of &#8220;optional&#8221; data. The idea is to model the constraints in the problem description, and resolve them in order to produce a cake. Solve it in any way you like, in whatever language. I&#8217;ve set up a template in Haskell (MaybeCake.hs), [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a programming puzzle I created, which deals with a bunch of dependent pieces of &#8220;optional&#8221; data. The idea is to model the constraints in the problem description, and resolve them in order to produce a cake. Solve it in any way you like, in whatever language. I&#8217;ve set up a template in Haskell (<a href="https://github.com/techtangents/maybecake/blob/master/MaybeCake.hs">MaybeCake.hs</a>), so you just have to define one function. I&#8217;ve also provided a solution (<a href="https://github.com/techtangents/maybecake/blob/master/MaybeCakeAnswer.hs">MaybeCakeAnswer.hs</a>). The Haskell source uses the Maybe data structure, but other solutions may be possible. <a href="https://github.com/techtangents/maybecake">github repo</a>.</p>
<p>Apologies if my recipes are rubbish &#8211; I&#8217;m not much of a baker <img src='http://www.techtangents.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Enjoy!</p>
<blockquote><p>I&#8217;d like a cake.</p>
<p>Ideally, I&#8217;d like to bake it myself, but if I don&#8217;t have the ingredients, I&#8217;ll buy one from the bakery (if they have one).</p>
<p>I can make 2 types of cake:</p>
<ul>
<li>My favourite is a mud cake (egg, chocolate, flour).</li>
<li>I can also make a flourless cake (egg, chocolate, cocoa).</li>
</ul>
<p>There might be some chocolate in the fridge or the pantry.<br />
There might be some flour in the pantry.<br />
There might be some cocoa in the pantry.</p>
<p>There might be an egg in the fridge, but I&#8217;d prefer a fresh one &#8211; maybe my chook laid one?</p>
<p>But I think I saw a taipan around the chicken coup yesterday &#8211; hopefully he didn&#8217;t get my chook!</p>
<p>So, do I get a cake and, if so, which one?</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.techtangents.com/the-maybe-cake-puzzle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java: How to return two values from a function (and other stories) (updated!)</title>
		<link>http://www.techtangents.com/java-how-to-return-two-values-from-a-function-and-other-stories/</link>
		<comments>http://www.techtangents.com/java-how-to-return-two-values-from-a-function-and-other-stories/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 22:42:44 +0000</pubDate>
		<dc:creator>techtangents</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.techtangents.com/?p=440</guid>
		<description><![CDATA[Updated: Code examples are now at: https://github.com/techtangents/java-return-values Don&#8217;t do this: public class Demo1 {    public static void main(final String[] args) {        final String[] ret = new String[2];        foo(ret, "ohai");        System.out.println("ret[0] = " + ret[0]);        System.out.println("ret[1] = " + ret[1]);    }    public static void foo(final String[] ret, final String input) {        ret[0] = "oh";        ret[1] = "no"; [...]]]></description>
			<content:encoded><![CDATA[<p>Updated: Code examples are now at: <a href="https://github.com/techtangents/java-return-values">https://github.com/techtangents/java-return-values</a></p>
<p>Don&#8217;t do this:</p>
<p><span style="font-family: monospace;"> </span></p>
<pre>public class Demo1 {
   public static void main(final String[] args) {
       final String[] ret = new String[2];
       foo(ret, "ohai");
       System.out.println("ret[0] = " + ret[0]);
       System.out.println("ret[1] = " + ret[1]);
   }

   public static void foo(final String[] ret, final String input) {
       ret[0] = "oh";
       ret[1] = "no";
   }
}</pre>
<p>&nbsp;</p>
<p>This is slightly better, but the type is too weak. A &#8220;String[]&#8221; has &#8220;n&#8221; values, not two.</p>
<pre><span style="font-family: monospace;">
<pre>public class Demo2 {
    public static void main(final String[] args) {
        final String[] ret = foo("ohai");
        System.out.println("ret[0] = " + ret[0]);
        System.out.println("ret[1] = " + ret[1]);
    }

    public static String[] foo(final String input) {
        return new String[] {"oh", "alright"};
    }
}</pre>
<p><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">Oh, yeah, this is the business. Tuples are where it's at. Type is strong - exactly two values are returned. Compiler enforces this.</span></p>
<p></span></pre>
<pre><span style="font-family: monospace;">
<pre>public class Demo3 {
    public static void main(final String[] args) {
        final Pair&lt;String, String&gt; ret = foo("ohai");
        System.out.println("ret.a = " + ret.a);
        System.out.println("ret.b = " + ret.b);
    }

    public static Pair&lt;String, String&gt; foo(final String input) {
        return Pair.p("oh", "yeah");
    }
}</pre>
<p>&nbsp;</p>
<p></span></pre>
<pre><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">The Pair class looks like this:</span></pre>
<pre><span style="font-family: monospace;">
<pre>public class Pair&lt;A, B&gt; {

    public final A a;
    public final B b;

    protected Pair(final A a, final B b) {
        this.a = a;
        this.b = b;
    }

    public static &lt;A, B&gt; Pair&lt;A, B&gt; p(final A a, final B b) {
        return new Pair&lt;A, B&gt;(a, b);
    }
}</pre>
<p>&nbsp;</p>
<p></span></pre>
<p><span style="font-family: monospace;"><span style="font-size: 12px; line-height: 18px; white-space: pre;"><br />
</span></span></p>
<p>Tuples are great general-purpose, but if you use a specific tuple of values all the time, you can always make a special-case structure instead:</p>
<pre><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 26px; font-weight: bold; line-height: 19px; white-space: normal;">
<pre>public class Demo4 {
    public static class Foo {
        private final String toaster;
        private final String muffin;

        private Foo(final String toaster, final String muffin) {
            this.toaster = toaster;
            this.muffin = muffin;
        }

        public static Foo nuFoo(final String toaster, final String muffin) {
            return new Foo(toaster, muffin);
        }

        public String toaster() {
            return toaster;
        }

        public String muffin() {
            return muffin;
        }
    }

    public static void main(final String[] args) {
        final Foo ret = foo("ohai");
        System.out.println("ret.toaster = " + ret.toaster());
        System.out.println("ret.muffin = " + ret.muffin());
    }

    public static Foo foo(final String input) {
        return Foo.nuFoo("oh", "yeah");
    }
}</pre>
<p>Private Constructors</p>
<p></span></pre>
<p>Ok, so why did I use a private constructor with a static &#8220;factory&#8221; method? So, I can change how I generate a Foo, without changing the call signature. Constructors aren&#8217;t the only way to create objects. Examples: &#8211; I might want to return a concrete subclass of Foo &#8211; I might want to return an anonymous subclass of Foo &#8211; I might want to return a Foo that I generate as a result of calling other functions</p>
<p>The static method also lets you perform effects in creating the object (e.g. get a Foo from the network) without there being actual side effects in a constructor (which you should absolutely NEVER do).</p>
<p>It also lets you have multiple &#8220;factory&#8221; methods, for different combinations of parameters, without chaining constructors, which is clumsy.</p>
<p>So, an example:</p>
<pre><span style="font-family: monospace;">
<pre>public class Demo5 {
    public abstract static class Foo {

        public abstract String toaster();
        public abstract String muffin();

        public static Foo nuFoo(final String toaster, final String muffin) {
            return new Foo() {
                @Override
                public String toaster() {
                    return toaster;
                }

                @Override
                public String muffin() {
                    return muffin;
                }
            };
        }
    }

    public static void main(final String[] args) {
        final Foo ret = foo("ohai");
        System.out.println("ret.toaster = " + ret.toaster());
        System.out.println("ret.muffin = " + ret.muffin());
    }

    public static Foo foo(final String input) {
        return Foo.nuFoo("oh", "yeah");
    }
}</pre>
<p>&nbsp;</p>
<p></span></pre>
<p>Notice how the &#8220;foo&#8221; and &#8220;callFoo&#8221; functions didn&#8217;t change as a result of this.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techtangents.com/java-how-to-return-two-values-from-a-function-and-other-stories/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entertaining the warranty return department</title>
		<link>http://www.techtangents.com/entertaining-the-warranty-return-department/</link>
		<comments>http://www.techtangents.com/entertaining-the-warranty-return-department/#comments</comments>
		<pubDate>Thu, 28 Jul 2011 22:29:42 +0000</pubDate>
		<dc:creator>techtangents</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.techtangents.com/?p=438</guid>
		<description><![CDATA[Dear warranty return department, Oh dear! My beloved SSD has departed from this world! Like a true rockstar, he shone too bright and died too young! Oh, cruel fate, to be thusly boned. Ask not for whom the bone bones, it bones for thee, dear Vertex. Please take care of my dearly departed as he [...]]]></description>
			<content:encoded><![CDATA[<p>Dear warranty return department,</p>
<blockquote><p>Oh dear! My beloved SSD has departed from this world! Like a true rockstar, he shone too bright and died too young! Oh, cruel fate, to be thusly boned. Ask not for whom the bone bones, it bones for thee, dear Vertex. Please take care of my dearly departed as he enters the next world &#8211; the warranty return department.</p>
<p>On Wednesday eve, around 6pm, he suffered a heart attack in his sleep, and was henceforth no longer recognised by the bios. Several attempts were made to resuscitate him (in a Dell Poweredge server and Vantec disk dock), but it was too late. The doctors pronounced him dead at 7:54am Friday 29th July.</p>
<p>He will be remembered as a rebel. Ahead of his time &#8211; a star performer and a true testament to his generation. He will be missed by friends, family and coworkers alike. May he rest in peace.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.techtangents.com/entertaining-the-warranty-return-department/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Emulating infix operator syntax in javascript</title>
		<link>http://www.techtangents.com/emulating-infix-operator-syntax-in-javascript/</link>
		<comments>http://www.techtangents.com/emulating-infix-operator-syntax-in-javascript/#comments</comments>
		<pubDate>Sat, 18 Jun 2011 11:51:15 +0000</pubDate>
		<dc:creator>techtangents</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.techtangents.com/?p=431</guid>
		<description><![CDATA[In Maths, we write 1 + 1, but in many programming languages this becomes prefix: +(1, 1) or plus(1, 1) or (plus 1 1) or number(1).plus(1). Many languages directly support an infix notation, e.g. Haskell and Scala. This is particularly nice as a way of unifying the concepts of operators and function while providing a [...]]]></description>
			<content:encoded><![CDATA[<p>In Maths, we write 1 + 1, but in many programming languages this becomes prefix: +(1, 1) or plus(1, 1) or (plus 1 1) or number(1).plus(1). Many languages directly support an infix notation, e.g. Haskell and Scala. This is particularly nice as a way of unifying the concepts of operators and function while providing a nice syntax for functions with symbolic names like +, -, &gt;&gt;=. I found a way of emulating this in Javascript.</p>
<p>In js, properties of objects can have any name, even if that name is a reserved word or invalid identifier. e.g. {&#8220;a&#8221; : 3, &#8220;&gt;&lt;!!&#8221;: 3, &#8220;private&#8221;: 4};. When you refer to a property, you can use either object.property or object["property"]. We&#8217;ll exploit the latter.</p>
<h3>Example 1: String Split</h3>
<p>For a simple example, say I want to split a string by a character.  There&#8217;s a function String.prototype.split for this, so I can write:<br />
&#8220;a,b,c&#8221;.split(&#8220;,&#8221;)</p>
<p>Let&#8217;s change it to a symbolic infix operator. Ideally, we&#8217;d like to write:<br />
&#8220;a,b,c&#8221; | &#8220;,&#8221;</p>
<p>We can come close:<br />
(&#8220;a,b,c&#8221;) ["|"] (&#8220;,&#8221;)</p>
<p>by doing:<br />
String.prototype["|"] = String.prototype.split</p>
<p>So, imagine all values are enclosed in () and all operators enclosed in [""] &#8211; we take this on as syntactic noise, but otherwise we have the desired syntax. The key thing is really getting rid of the &#8220;.&#8221; to make it look more of an operator than &#8220;invoking a method on an object&#8221;.</p>
<h3>Example 2: &gt;&gt;= on Maybe</h3>
<p>&gt;&gt;= is the monadic bind operator in Haskell. If you don&#8217;t fully understand that sentence, please stop reading and go learn it, it kicks ass and is far more important than this post <img src='http://www.techtangents.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>My favourite monad is Maybe. Here&#8217;s a simple example of binding over Maybes in Haskell:</p>
<p>f = \x -&gt; if (x &gt; 3) then Just(x + 1) else Nothing;<br />
g = \y -&gt; y &gt;&gt;= f &gt;&gt;= f</p>
<p>In javascript, it&#8217;s tricky to write the monad abstraction, but simple to   write specific monads &#8211; you just have to repeat yourself a lot. I&#8217;ve cooked up a very basic Maybe in Javascript which defines a &gt;&gt;= operator. The equivalent example looks like this:</p>
<p>var f = function(x) {  return x &gt; 3 ? Just(x + 1) : Nothing; };<br />
var g = function(y) {  return (y) ["&gt;&gt;="] (f) ["&gt;&gt;="] (f); };</p>
<p>The code is up at <a href="https://github.com/techtangents/jsinfix">https://github.com/techtangents/jsinfix</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.techtangents.com/emulating-infix-operator-syntax-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Type Algebra: 2+2 = 2*2</title>
		<link>http://www.techtangents.com/2plus2/</link>
		<comments>http://www.techtangents.com/2plus2/#comments</comments>
		<pubDate>Fri, 27 May 2011 11:45:42 +0000</pubDate>
		<dc:creator>techtangents</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.techtangents.com/?p=425</guid>
		<description><![CDATA[&#8220;Since 2*2 == 2+2, then (Boolean, Boolean) is equivalent to Boolean &#124; Boolean&#8221; &#8211; Tony Morris Word. Below is how you can construct these two types in Haskell, and show their equivalence. It&#8217;s interesting the different ways each type encodes the same data. One encodes the two booleans as the first and second member of [...]]]></description>
			<content:encoded><![CDATA[<p>&#8220;Since 2*2 == 2+2, then (Boolean, Boolean) is equivalent to Boolean | Boolean&#8221; &#8211; Tony Morris</p>
<p>Word.</p>
<p>Below is how you can construct these two types in Haskell, and show their equivalence. It&#8217;s interesting the different ways each type encodes the same data. One encodes the two booleans as the first and second member of the pair, whereas the other encodes one boolean as &#8220;which constructor did you pick&#8221; and the other as &#8220;what boolean did you pass to the constructor&#8221;. I think the names of the two constructors (&#8220;TrueAnd&#8221; and &#8220;FalseAnd&#8221;) highlight how the encoding works.</p>
<pre>module BoolEquivalent where

import Test.QuickCheck

data B2 = TrueAnd Bool | FalseAnd Bool
 deriving (Eq, Show)

data P2 = P2 (Bool, Bool)
 deriving (Eq, Show)

pToB :: P2 -&gt; B2
pToB (P2 (True, x)) = TrueAnd x
pToB (P2 (False, x)) = FalseAnd x

bToP :: B2 -&gt; P2
bToP (TrueAnd x) = P2 (True, x)
bToP (FalseAnd x) = P2 (False, x)

instance Arbitrary B2 where
 arbitrary = oneof $ return `fmap` [TrueAnd True, TrueAnd False, FalseAnd True, FalseAnd False]

instance Arbitrary P2 where
 arbitrary = oneof $ (return . P2) `fmap` [(True, True), (True, False), (False, True), (False, False)]

prop_inverse1 :: B2 -&gt; Bool
prop_inverse1 x = (pToB . bToP) x == x

prop_inverse2 :: P2 -&gt; Bool
prop_inverse2 x = (bToP . pToB) x == x

go = do
 quickCheck prop_inverse1
 quickCheck prop_inverse2</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.techtangents.com/2plus2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dependently-typed, fine-grained effect types for safe parallelism</title>
		<link>http://www.techtangents.com/dependently-typed-fine-grained-effect-types-for-safe-parallelism/</link>
		<comments>http://www.techtangents.com/dependently-typed-fine-grained-effect-types-for-safe-parallelism/#comments</comments>
		<pubDate>Mon, 02 May 2011 09:54:21 +0000</pubDate>
		<dc:creator>techtangents</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.techtangents.com/?p=422</guid>
		<description><![CDATA[Pure functions are parallelisable. That is, two pure functions may be run in parallel or in sequence, and yield the same result (provided that there is no data dependency between the two). Impure functions do not have this property. As they contain side effects, evaluation order matters. When attempting to parallelise, parallel sequences of effects [...]]]></description>
			<content:encoded><![CDATA[<p><!-- 		@page { margin: 2cm } 		P { margin-bottom: 0.21cm } -->Pure functions are parallelisable. That is, two pure functions may be run in parallel or in sequence, and yield the same result (provided that there is no data dependency between the two).</p>
<p>Impure functions do not have this property. As they contain side effects, evaluation order matters. When attempting to parallelise, parallel sequences of effects may have interrelations which result in different semantics when run in parallel or in sequence.</p>
<p>Yet, we can intuit that some effects are safe to parallelise. Take for example, the following haskell functions:</p>
<p>write1 :: IO ()<br />
write1 = writeFile &#8220;/tmp/file1&#8243; &#8220;a&#8221;</p>
<p>write2 :: IO ()<br />
write2 = writeFile &#8220;/tmp/file2&#8243; &#8220;b&#8221;</p>
<p>both :: IO ()<br />
both = write1 &gt;&gt; write2</p>
<p>“both” writes the two files in sequence&#8230; however, writing them in parallel would give the same output. Contrast to the following:</p>
<p>write1 :: IO ()<br />
write1 = writeFile &#8220;/tmp/file1&#8243; &#8220;a&#8221;</p>
<p>write2 :: IO ()<br />
write2 = writeFile &#8220;/tmp/file1&#8243; &#8220;b&#8221;</p>
<p>both :: IO ()<br />
both = write1 &gt;&gt; write2</p>
<p>As &#8216;write1&#8242; and &#8216;write2&#8242; are both writing to the same file, order of execution matters, and it is not safe to parallelise.</p>
<p>So, one set of functions is safe to parallelise, but the other is not. If the programmer wants to take advantage of parallelism, it is up to them to guarantee the safety of it. This is risky. It would be better if there was a static guarantee, checked by the compiler. Let&#8217;s encode this information in the type system.</p>
<p>All of the above functions are of type IO (). This is a very broad type &#8211; any effect can be performed within IO. We need more specific types, for specific effects.</p>
<p>Firstly, we can identify that the writeFile function performs file IO. Let&#8217;s consider an effect type “FileIO”. So, writeFile&#8217;s type would become “FilePath -&gt; String -&gt; FileIO ()”. This doesn&#8217;t solve the problem above, however, imagine if we had a similar effect type “NetworkIO”.  A function of type “NetworkIO ()” could safely run in parallel with a function of type “FileIO ()”, since network and file IO will not impact each other.</p>
<p>To directly solve the problem above, we need to go more fine-grained. We know that (writeFile f s) will only write to file “s”. Since s is a value, we need dependent types. The type of writeFile now depends on the argument to parameter s.</p>
<p>If we modify Haskell syntax to include dependent types, we could denote this as:</p>
<p>writeFile :: (a :: FilePath) -&gt; String -&gt; FileIO a ()</p>
<p>FileIO is now a type constructor with one value parameter and one type parameter. The value parameter denotes what file the effect is allowed to access.</p>
<p>With this in mind, the two functions above could be written as:</p>
<p>write1 :: FileIO “/tmp/file1” ()<br />
write1 = writeFile &#8220;/tmp/file1&#8243; &#8220;a&#8221;</p>
<p>write2 :: FileIO “/tmp/file2” ()<br />
write2 = writeFile &#8220;/tmp/file2&#8243; &#8220;b&#8221;</p>
<p>The paths are duplicated between the functions&#8217; type signatures and declaration. A new syntax could allow refactoring of this. e.g.</p>
<p>write1 :: a = “/tmp/file1” =&gt; FileIO a ()<br />
write1 = writeFile a &#8220;a&#8221;</p>
<p>write2 :: a = “/tmp/file2” =&gt; FileIO a ()<br />
write2 = writeFile a &#8220;b&#8221;</p>
<p>We now have enough information in the types to know that the two operations are independent, and can be safely parallelised.</p>
<p>So, what would the type of “both” be? “both” is a function that takes no arguments, and writes to files “/tmp/file1” and “/tmp/file2”. Below are a few possible approaches, and the resulting type signatures.</p>
<ol>
<li>Create a type FileIOs that has a 	value parameter of type [FilePath].<br />
write1 :: FileIO 	[“/tmp/file1”] ()<br />
write2 :: FileIO [“/tmp/file2”] ()<br />
both :: FileIOs [“/tmp/file1”, “/tmp/file2”] ()</li>
<li>Just use a FileIO type that takes 	a list of files.<br />
write1 :: FileIO [“/tmp/file1”] ()<br />
write1 	:: FileIO [“/tmp/file2”] ()<br />
both :: FileIO [“/tmp/file1”, 	“/tmp/file2”] ()</li>
<li>Introduce a scheme of conversions 	between types. Possible options include:
<ol>
<li>An implicit conversion. “FileIO 		child” would automatically widen to “FileIO ancestor”.</li>
<li>An explicit conversion to a Maybe 		type:<br />
widen :: (y :: FilePath) -&gt; FileIO x  -&gt; Maybe 		(FileIO y)</li>
<li>An explicit conversion to a 		common type. e.g.<br />
extend :: (z = commonAncestor x y) =&gt; 		FileIO x -&gt; FileIO y -&gt; FileIO z</li>
<li>Automatic widening within the 		effect tracking system.</li>
<li>Any function with parameters of 		type FileIO x and FileIO y has type FileIO “/”</li>
</ol>
</li>
</ol>
<p>There are obviously some challenges in implementing these schemes:</p>
<ol>
<li>Some of the information we want to 	put in the type system may not be available until runtime &#8211; e.g. 	what is the common parent of two files x and y?</li>
<li>What happens in the case of 	symbolic links and mounted drives?</li>
</ol>
<p>These would require further research.</p>
<p><strong>Conclusion</strong></p>
<p>The underlying concept is that of gaining leverage by preserving information. The implementation of “writeFile” has information that denotes that it can only write to one file, however, we throw this information away when we widen to IO. By preserving it and encoding it in the type system, we acquire useful static information about our programs. This can give effectful code some of the priviledges that only pure code currently enjoys, such as parallelism.</p>
<p>I suspect that it would also improve our ability to verify effectful code &#8211; a problem I described in <a href="/purity-and-testability/">a previous post</a>. If I know that a function can only perform file IO in a certain folder, I can test by checking for evidence of filesystem changes in that folder. I know that it didn&#8217;t write anywhere else, and I know that it didn&#8217;t print to the screen or open network sockets.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techtangents.com/dependently-typed-fine-grained-effect-types-for-safe-parallelism/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Purity and Testability</title>
		<link>http://www.techtangents.com/purity-and-testability/</link>
		<comments>http://www.techtangents.com/purity-and-testability/#comments</comments>
		<pubDate>Fri, 08 Apr 2011 15:19:45 +0000</pubDate>
		<dc:creator>techtangents</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.techtangents.com/?p=419</guid>
		<description><![CDATA[Only pure functions are truly testable. Moreover, the relationship between purity and testability forms a solid justification for functional programming. Let me explain&#8230; For starters, what is a pure function? A function without side effects. A function in the mathematical sense. Now, a function is a type of relation (set of ordered pairs), where each [...]]]></description>
			<content:encoded><![CDATA[<p>Only pure functions are truly testable. Moreover, the relationship between purity and testability forms a solid justification for functional programming.</p>
<p>Let me explain&#8230;</p>
<p>For starters, what is a pure function? A function without side effects. A function in the mathematical sense. Now, a function is a type of relation (set of ordered pairs), where each element of the domain corresponds to exactly one element of the range. A (total) function is also defined for each element of the domain, unlike a partial function, which is not.</p>
<p>So, what does this mean for testability? It means that I can potentially write a test which runs the function over each element of the domain, and asserts that the correct element of the range is returned. One simple way of doing this is to actually spell out the pairs that consitute the expected definition of the function, then map the function over its domain and zip the results with the domain, and then compare the two.</p>
<p>I&#8217;ll give an example with a boolean domain, as it has a small domain. I&#8217;ll use Haskell for simplicity.</p>
<p>Let&#8217;s look at the function isNot, which flips a boolean.</p>
<p>isNot :: Bool -&gt; Bool<br />
isNot x = if (x == True) False else True</p>
<p>Alternatively, pattern matching gives us a syntax which looks very much like the relation pairs:</p>
<p>isNot&#8217; :: Bool -&gt; Bool<br />
isNot&#8217; True = False<br />
isNot&#8217; False = True</p>
<p>Now, we could test this using the following functions &#8211; the both evaluate to True:</p>
<p>testTrue = (isNot True) == False<br />
testFalse = (isNot False) == True</p>
<p>The domain is {True, False}, and the expected relation is {(True, False), (False, True)}. So, let&#8217;s do the map and zip thing. The &#8216;spellOut&#8217; function does this for any function and any domain.</p>
<p>spellOut :: (a -&gt; b) -&gt; [a] -&gt; [(a, b)]<br />
spellOut f domain = zip domain (fmap f domain)</p>
<p>So, then we can say this, which is a complete test of this function.</p>
<p>test = (spellOut isNot [True, False]) == [(True, False), (False, True)]</p>
<p>Pretty cool, huh? Of course, there are many ways to test a function, this just works well for the demonstration.</p>
<p>Now, what happens if we throw a side-effect into the mix? The mathematical notion of a function has no concept of effects &#8211; it&#8217;s just a (total) relation between a domain and a range. Mathematical functions are <em>defined</em>, they don&#8217;t <em>do things</em>, they just exist. The concept of a side effect is introduced just so that software can do useful things.</p>
<p>In the pure function example, we tested by computing the (domain-value, range-value) pairs, and comparing with our expectations. An impure function still has a domain and range, but it also has <em>other stuff that happens</em>. We can compare domain/range pairs&#8230; but how do we test the other stuff?</p>
<p>There is nothing in the return value that indicates what side effect has been performed (I&#8217;ll get to effect tracking in a minute). Imagine if we could get a value that definitively represented a side effect that was performed&#8230; if that value was part of the return value, then we could compare that value against our expected. No such concept exists &#8211; a side effect is something that happened, it can be described, but it cannot be bottled up into a value.</p>
<p>So, what can we do instead? Well, we can execute the side-effecting function, then look for evidence that the expected side effect happened. This is better than nothing, but it is still not a true test of the side effect &#8211; you are only looking at some state that could have been influenced by the expected side effect. It&#8217;s like investigating crime &#8211; looking for clues in a crime scene, relying on witness testimony, maybe you&#8217;ll get a conviction, maybe not. Maybe someone is lying. Did a crucial piece of evidence go missing? Did someone alter the crime scene? What if we send an innocent person to jail, or let the guilty party go free?</p>
<p>Perhaps the effect didn&#8217;t fire, but some background process did a similar thing (false positive). Perhaps the effect did it&#8217;s job, but then a background process reverted it (false negative). There is no way of knowing.</p>
<p>Worse, the Observer Effect comes into play &#8211; observing an event changes the event. In our case, in order to observe the side effect, we are performing another side effect. As such, there are two effects occurring, whereas in production there would only be one. Your extra effect could give you false positives or false negatives.</p>
<p>It gets even worse than this! You are looking for clues that a certain effect was performed, but what if the function you&#8217;re testing performed <em>another</em> effect? You cannot test that a function does not perform any other effects in addition to the one you are observing.</p>
<p>Now, there is some good news here, in the form of Effect Tracking. Effect Tracking is compiler-enforced acknowledgement of side effects. That is, if a function contains code that can performs a side effect of type X, then X must be part of its type signature. This will tell you that no effects of type Y can occur&#8230; but you still have many of the problems above when looking for evidence of type X. Effect Tracking also lets you easily see which functions are pure and which are not. It also encourages you to write more pure functions. And, in Haskell, effects are tracked using monads, so you have all the normal monadic tools available to help you deal with them. The flipside is that, at least initially, it feels like you are spending a lot of time fighting with the effect tracking and going in and out of monadic code&#8230; there&#8217;s a learning curve, but it does become easier, and the benefits are massive. And I&#8217;m definitely up for learning something hard if it improves my code.</p>
<p>So, given all of these problems, I&#8217;m of the opinion that side effecting code is not testable. Of course, this comes down to the definition of &#8220;testable&#8221; and, furthermore, the definition of &#8220;test&#8221;. What does it mean to test a piece of code? What does it mean for a piece of code to be &#8220;tested&#8221;?</p>
<p>In the first example, I wrote a test that definitively and exhaustively proved the relationship between the domain and range. That code is tested. No arguments there.</p>
<p>What about a side-effecting function? We can write a &#8220;test&#8221; that executes the code and does some assertions, but it&#8217;s not the same. We haven&#8217;t proved anything. Certain defects may have resulted in test failures, and certain correct code may have passed, but we have no guarantees. That&#8217;s a far weaker position to be in&#8230; but maybe that&#8217;s the best we can do. But if it&#8217;s the best we can do, we want to write code in a way that minimizes how often we are in this position.</p>
<p>This really highlights the importance of keeping your code as pure as possible. Keeping a clear separation between logic and effect&#8230; and pushing that boundary hard. This is the essence of functional programming.</p>
<p>For me, testability is the number one justification for functional programming, and is how I got into it. TDD got me into writing tests, and I eventually realised that the tests were far easier to write, and far more reliable, when the code was pure. Of course, there are many other benefits of functional programming, but this has got to be the knockout punch.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techtangents.com/purity-and-testability/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>BSD Slice Calculator</title>
		<link>http://www.techtangents.com/bsd-slice-calculator/</link>
		<comments>http://www.techtangents.com/bsd-slice-calculator/#comments</comments>
		<pubDate>Fri, 08 Apr 2011 13:21:06 +0000</pubDate>
		<dc:creator>techtangents</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.techtangents.com/?p=416</guid>
		<description><![CDATA[The GPART command for FreeBSD does the job, but isn&#8217;t that friendly. In particular, specifying partition sizes in logical blocks is confusing. You need to do some planning to figure out your partition layout, and then translate that into gpart commands. The BSD Slice Calculator helps with this. Plug in the values in the blue [...]]]></description>
			<content:encoded><![CDATA[<p>The GPART command for FreeBSD does the job, but isn&#8217;t that friendly. In particular, specifying partition sizes in logical blocks is confusing. You need to do some planning to figure out your partition layout, and then translate that into gpart commands.</p>
<p>The BSD Slice Calculator helps with this. Plug in the values in the blue cells, and it&#8217;ll give you the start and size of each partition in blocks, which you can then plug into gpart. Download it from <a href="http://www.techtangents.com/media/bsdslicecalculator/bsd_slice_calculator.ods">here</a> (ods spreadsheet).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techtangents.com/bsd-slice-calculator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Timeout loops</title>
		<link>http://www.techtangents.com/timeout-loops/</link>
		<comments>http://www.techtangents.com/timeout-loops/#comments</comments>
		<pubDate>Tue, 08 Mar 2011 10:51:15 +0000</pubDate>
		<dc:creator>techtangents</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.techtangents.com/?p=410</guid>
		<description><![CDATA[RE: Doug Crockford&#8217;s talk at http://developer.yahoo.com/yui/theater/video.php?v=crockonjs-3 In slide 43, there&#8217;s a fade out algorithm that looks like this. He&#8217;s using it to illustrate closure &#8211; in this case, the variables &#8216;level&#8217; and &#8216;dom&#8217;: function fade(id) { var dom = document.getElementById(id), level = 1; function step() { var h = level.toString(16); dom.style.backgroundColor = '#FFFF' + h [...]]]></description>
			<content:encoded><![CDATA[<p>RE: Doug Crockford&#8217;s talk at <a href="http://developer.yahoo.com/yui/theater/video.php?v=crockonjs-3">http://developer.yahoo.com/yui/theater/video.php?v=crockonjs-3</a></p>
<p>In slide 43, there&#8217;s a fade out algorithm that looks like this. He&#8217;s using it to illustrate closure &#8211; in this case, the variables &#8216;level&#8217; and &#8216;dom&#8217;:</p>
<pre>
function fade(id) {
    var dom = document.getElementById(id),
        level = 1;
    function step() {
        var h = level.toString(16);
        dom.style.backgroundColor = '#FFFF' + h + h;
        if (level < 15) {
            level += 1;
            setTimeout(step, 100);
        }
    }
    setTimeout(step, 100);
}
</pre>
<p>Now this struck me as strange - mutation within a recursive algorithm. This inspired me to do a couple of rewrites that avoid that, whilst providing some interesting abstractions that separate concerns.</p>
<p>1. Separating out the notion of a delayed function.<br />
timedOut is a higher-order that wraps a function in a timeout loop. This makes the code feel more like a normal recursive algorithm. Notice the step(level + 1) replaces the mutation.</p>
<pre>
function timedOut(fn, delay) {
    return function() {
        var args = arguments;
        setTimeout(function() {
            return fn.apply(this, args);
        }, delay);
    };
}

function fade(id) {
    var dom = document.getElementById(id);
    var step = timedOut(function(level) {
        var h = level.toString(16);
        dom.style.backgroundColor = '#FFFF' + h + h;
        if (level < 15) {
            step(level + 1);
        }
    }, 100);
    step(1);
}
</pre>
<p>2. Separating out the notion of a timeout loop.<br />
I really like this one. It clearly separates the rendering logic from the mechanism that recurses n times.</p>
<pre>
function timeoutLoop(fn, delay, start, end) {
    var t = function(current) {
        setTimeout(function() {
            fn(current);
            if (current < end) {
                t(current + 1);
            }
        }, delay);
    };
    t(start);
}

function fade(id) {
    var dom = document.getElementById(id);
    var step = function(level) {
        var h = level.toString(16);
        dom.style.backgroundColor = '#FFFF' + h + h;
    };
    timeoutLoop(step, 100, 1, 15);
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.techtangents.com/timeout-loops/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

