<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.0.5" -->
<rss version="2.0" 
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>λ Tony's  blog λ</title>
	<link>http://blog.tmorris.net</link>
	<description>The weblog of Tony Morris</description>
	<pubDate>Thu, 17 Jul 2008 20:15:37 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.0.5</generator>
	<language>en</language>
			<item>
		<title>Haskell exercises for beginners</title>
		<link>http://blog.tmorris.net/haskell-exercises-for-beginners/</link>
		<comments>http://blog.tmorris.net/haskell-exercises-for-beginners/#comments</comments>
		<pubDate>Thu, 17 Jul 2008 01:33:07 +0000</pubDate>
		<dc:creator>Tony Morris</dc:creator>
		
		<category>Programming</category>

		<guid isPermaLink="false">http://blog.tmorris.net/haskell-exercises-for-beginners/</guid>
		<description><![CDATA[The exercises below are similar to my previous &#8216;Scala exercises for beginners&#8217;, except the rules a little clearer. For those of who have emailed me or submitted responses here on the blog, I will get around to providing you feedback, however, I&#8217;d prefer to do so on the revised version of the Exercises since then [...]]]></description>
			<content:encoded><![CDATA[<p>The exercises below are similar to my previous &#8216;Scala exercises for beginners&#8217;, except the rules a little clearer. For those of who have emailed me or submitted responses here on the blog, I will get around to providing you feedback, however, I&#8217;d prefer to do so on the revised version of the Exercises since then I can maintain a bit of clarity in explaining the solutions; specifically, why one may be preferred over another. I hope you don&#8217;t mind.</p>
<p>If you have not used Haskell before, download and install <a href="http://haskell.org/ghc" onclick="javascript:pageTracker._trackPageview('/outbound/article/haskell.org');">GHC</a>, start up the interpreter (ghci) and load the source file. e.g. <code>:load Exercises.hs</code> If you are on Debian, you can install GHC and start the interpreter with: <code>apt-get install ghc6 &#038;&#038; ghci</code>.</p>
<p>The source file below can be found <a href="http://projects.tmorris.net/public/sb/Exercises.hs" >here</a>.</p>
<pre>
{-
The 'Scala exercises for beginners' set rules about what you were not permitted to use.
This is because you were permitted to use some functions, but not others. This led to
some amount of confusion (sorry). Instead, this time, I will define my own data types.
One is equivalent to Haskell's list [], although without the syntactic support and the
other is the set of natural numbers (0 onward). I will also predefine some useful
functions that you might consider using to solve each problem. That way, I needn't set
any rules; you are very much free to do what you want (Although, converting between
this type and [] is considered cheating, as you might expect <img src='http://blog.tmorris.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .

I will consider converting the Scala exercises to use a similar strategy in a second
revision to prevent this confusion.

TOTAL marks:    /66
-}

module Exercises where

import Prelude hiding (sum, length, map, filter, maximum, reverse, succ, pred)

-- The custom list type
data List t = Nil | Cons t (List t)

instance (Show t) => Show (List t) where
  show = show . toList
    where
    -- unfoldr, but let's not import Data.List
    toList Nil = []
    toList (Cons h t) = h : toList t

-- the custom numeric type
data Natural = Zero | Succ Natural
one = Succ Zero
two = Succ one

instance Show Natural where
  show = show . toInt
    where
    toInt Zero = 0
    toInt (Succ x) = 1 + toInt x

-- functions over Natural that you may consider using
succ :: Natural -> Natural
succ = Succ

pred :: Natural -> Natural
pred Zero = error "bzzt. Zero has no predecessor in naturals"
pred (Succ x) = x

-- functions over List that you may consider using
foldRight :: (a -> b -> b) -> b -> List a -> b
foldRight _ b Nil = b
foldRight f b (Cons h t) = f h (foldRight f b t)

foldLeft :: (b -> a -> b) -> b -> List a -> b
foldLeft _ b Nil = b
foldLeft f b (Cons h t) = let b' = f b h in b' `seq` foldLeft f b' t

reduceRight :: (a -> a -> a) -> List a -> a
reduceRight _ Nil = error "bzzt. reduceRight on empty list"
reduceRight f (Cons h t) = foldRight f h t

reduceLeft :: (a -> a -> a) -> List a -> a
reduceLeft _ Nil = error "bzzt. reduceLeft on empty list"
reduceLeft f (Cons h t) = foldLeft f h t

unfold :: (b -> Maybe (a, b)) -> b -> List a
unfold f b = case f b of Just (a, b') -> a `Cons` unfold f b'
                         Nothing -> Nil

-- Exercises

-- Exercise 1
-- Relative Difficulty: 1
-- Correctness: 2.0 marks
-- Performance: 0.5 mark
-- Elegance: 0.5 marks
-- Total: 3
add :: Natural -> Natural -> Natural
add = error "todo"

-- Exercise 2
-- Relative Difficulty: 2
-- Correctness: 2.5 marks
-- Performance: 1 mark
-- Elegance: 0.5 marks
-- Total: 4
sum :: List Int -> Int
sum = error "todo"

-- Exercise 3
-- Relative Difficulty: 2
-- Correctness: 2.5 marks
-- Performance: 1 mark
-- Elegance: 0.5 marks
-- Total: 4
length :: List a -> Int
length = error "todo"

-- Exercise 4
-- Relative Difficulty: 5
-- Correctness: 4.5 marks
-- Performance: 1.0 mark
-- Elegance: 1.5 marks
-- Total: 7
map :: (a -> b) -> List a -> List b
map = error "todo"

-- Exercise 5
-- Relative Difficulty: 5
-- Correctness: 4.5 marks
-- Performance: 1.5 marks
-- Elegance: 1 mark
-- Total: 7
filter :: (a -> Bool) -> List a -> List a
filter = error "todo"

-- Exercise 6
-- Relative Difficulty: 5
-- Correctness: 4.5 marks
-- Performance: 1.5 marks
-- Elegance: 1 mark
-- Total: 7
append :: List a -> List a -> List a
append = error "todo"

-- Exercise 7
-- Relative Difficulty: 5
-- Correctness: 4.5 marks
-- Performance: 1.5 marks
-- Elegance: 1 mark
-- Total: 7
flatten :: List (List a) -> List a
flatten = error "todo"

-- Exercise 8
-- Relative Difficulty: 7
-- Correctness: 5.0 marks
-- Performance: 1.5 marks
-- Elegance: 1.5 mark
-- Total: 8
flatMap :: List a -> (a -> List b) -> List b
flatMap = error "todo"

-- Exercise 9
-- Relative Difficulty: 8
-- Correctness: 3.5 marks
-- Performance: 3.0 marks
-- Elegance: 2.5 marks
-- Total: 9
maximum :: List Int -> Int
maximum = error "todo"

-- Exercise 10
-- Relative Difficulty: 10
-- Correctness: 5.0 marks
-- Performance: 2.5 marks
-- Elegance: 2.5 marks
-- Total: 10
reverse :: List a -> List a
reverse = error "todo"
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.tmorris.net/haskell-exercises-for-beginners/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Scala exercises for beginners</title>
		<link>http://blog.tmorris.net/scala-exercises-for-beginners/</link>
		<comments>http://blog.tmorris.net/scala-exercises-for-beginners/#comments</comments>
		<pubDate>Tue, 15 Jul 2008 01:12:51 +0000</pubDate>
		<dc:creator>Tony Morris</dc:creator>
		
		<category>Programming</category>

		<guid isPermaLink="false">http://blog.tmorris.net/scala-exercises-for-beginners/</guid>
		<description><![CDATA[The following exercises have come from of a course that I give on Functional Programming. I have assigned them difficulty ratings to make it a bit more exciting. Download the compilable source code from here or find it below. Enjoy  
These exercises can be translated into any language powerful enough to possess algebraic data [...]]]></description>
			<content:encoded><![CDATA[<p>The following exercises have come from of a course that I give on Functional Programming. I have assigned them difficulty ratings to make it a bit more exciting. Download the compilable source code from <a href="http://projects.tmorris.net/public/sb/Exercises.scala" >here</a> or find it below. Enjoy <img src='http://blog.tmorris.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>These exercises can be translated into <strong>any language powerful enough to possess algebraic data types and case matching</strong> <em>(yes, I am talking to <a href="http://beust.com/weblog/archives/000490.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/beust.com');">you</a>)</em>. Haskell is another such language and I will convert these exercises to Haskell if prompted.</p>
<pre>
// You are not permitted to use these List methods:
// * length
// * map
// * filter
// * ::: (and variations such as ++)
// * flatten
// * flatMap
// * reverse (and variations i.e. reverseMap, reverse_:::)
// This also means you are not permitted to use for-comprehensions on Lists.
// You are permitted to use the functions you write yourself. For example, Exercise 2 may use Exercise 1 or Exercise 3.
// Using permitted existing methods where appropriate will attract marks for elegance.

// TOTAL marks:    /66

object Exercises {
  def succ(n: Int) = n + 1
  def pred(n: Int) = n - 1

  // Exercise 1
  // Relative Difficulty: 1
  // Correctness: 2.0 marks
  // Performance: 0.5 mark
  // Elegance: 0.5 marks
  // Total: 3
  def add(x: Int, y: Int): Int = error("todo: Assume x and y are 0 or positive. Do not use + or - on Int. Only permitted to use succ/pred (above).")

  // Exercise 2
  // Relative Difficulty: 2
  // Correctness: 2.5 marks
  // Performance: 1 mark
  // Elegance: 0.5 marks
  // Total: 4
  def sum(x: List[Int]): Int = error("todo")

  // Exercise 3
  // Relative Difficulty: 2
  // Correctness: 2.5 marks
  // Performance: 1 mark
  // Elegance: 0.5 marks
  // Total: 4
  def length[A](x: List[A]): Int = error("todo")

  // Exercise 4
  // Relative Difficulty: 5
  // Correctness: 4.5 marks
  // Performance: 1.0 mark
  // Elegance: 1.5 marks
  // Total: 7
  def map[A, B](x: List[A], f: A => B): List[B] = error("todo")

  // Exercise 5
  // Relative Difficulty: 5
  // Correctness: 4.5 marks
  // Performance: 1.5 marks
  // Elegance: 1 mark
  // Total: 7
  def filter[A](x: List[A], f: A => Boolean): List[A] = error("todo")

  // Exercise 6
  // Relative Difficulty: 5
  // Correctness: 4.5 marks
  // Performance: 1.5 marks
  // Elegance: 1 mark
  // Total: 7
  def append[A](x: List[A], y: List[A]): List[A] = error("todo")

  // Exercise 7
  // Relative Difficulty: 5
  // Correctness: 4.5 marks
  // Performance: 1.5 marks
  // Elegance: 1 mark
  // Total: 7
  def concat[A](x: List[List[A]]): List[A] = error("todo")

  // Exercise 8
  // Relative Difficulty: 7
  // Correctness: 5.0 marks
  // Performance: 1.5 marks
  // Elegance: 1.5 mark
  // Total: 8
  def concatMap[A, B](x: List[A], f: A => List[B]): List[B] = error("todo")

  // Exercise 9
  // Relative Difficulty: 8
  // Correctness: 3.5 marks
  // Performance: 3.0 marks
  // Elegance: 2.5 marks
  // Total: 9
  def maximum(x: List[Int]): Int = error("todo")

  // Exercise 10
  // Relative Difficulty: 10
  // Correctness: 5.0 marks
  // Performance: 2.5 marks
  // Elegance: 2.5 marks
  // Total: 10
  def reverse[A](x: List[A]): List[A] = error("todo")
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.tmorris.net/scala-exercises-for-beginners/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Just an observation</title>
		<link>http://blog.tmorris.net/just-an-observation/</link>
		<comments>http://blog.tmorris.net/just-an-observation/#comments</comments>
		<pubDate>Mon, 07 Jul 2008 06:51:07 +0000</pubDate>
		<dc:creator>Tony Morris</dc:creator>
		
		<category>Programming</category>

		<guid isPermaLink="false">http://blog.tmorris.net/just-an-observation/</guid>
		<description><![CDATA[When some programmers pick up a functional programming language like Microsoft Excel, they stop caring about identifier names.

A1 = blah
B1 = function(A1, C2)
...

Can this observation be explained while maintaining consistency? I think it can.

]]></description>
			<content:encoded><![CDATA[<p>When some programmers pick up a functional programming language like Microsoft Excel, they stop caring about identifier names.</p>
<pre>
A1 = blah
B1 = function(A1, C2)
...
</pre>
<p>Can this observation be explained while maintaining consistency? I think it can.
</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tmorris.net/just-an-observation/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Implicits for the Fearless</title>
		<link>http://blog.tmorris.net/implicits-for-the-fearless/</link>
		<comments>http://blog.tmorris.net/implicits-for-the-fearless/#comments</comments>
		<pubDate>Fri, 04 Jul 2008 23:48:06 +0000</pubDate>
		<dc:creator>Tony Morris</dc:creator>
		
		<category>Programming</category>

		<guid isPermaLink="false">http://blog.tmorris.net/implicits-for-the-fearless/</guid>
		<description><![CDATA[Some programmers are married to the imperative, side-effecting mindset. This makes them fearful of Scala&#8217;s implicit keyword (among many other high-level programming constructs and abstractions). You can read all sorts of amateurish criticism of this language construct on various websites, but I plan to show why they are a necessity to the language being useful [...]]]></description>
			<content:encoded><![CDATA[<p>Some programmers are married to the imperative, side-effecting mindset. This makes them fearful of Scala&#8217;s <code>implicit</code> keyword (among many other high-level programming constructs and abstractions). You can read all sorts of amateurish criticism of this language construct on various websites, but I plan to show why they are a necessity to the language being useful (in the intellectually true and meaningful sense &mdash; not in a &#8220;Java&#8221; &#8220;pragmatist&#8221; sense (I know I&#8217;m treading on thin ice here, but the point is worthwhile)).</p>
<p>I also do not plan to address the amateurish claims specifically, since if you are like me, you simply acknowledge their existence, feel a bit sad, then get over it and move on. I mention these cases so that they can be contrasted to my plan to address a discussion I had with someone (who shall remain nameless for now and leave it up to them if they wish to reveal themselves) who put forward an <em>intellectually constructed</em> argument about why they can/should be eliminated. These kind of discussions are very purposeful. While my opponent&#8217;s argument was well thought-out (in contrast to the aforementioned), I still think it is wrong. Here is why.</p>
<p>You can do away with <code>implicit</code> definitions in favour of named functions with partial application. This is true, but is it <em>useful</em>? Furthermore, Scala is not exactly friendly to partially applying function arguments, requiring varying levels of awkwardness in certain contexts. I will assume, since I am a nice guy, that this is not the case. I will now alter the argument to what I consider to be equivalent, &#8220;Haskell can do away with type-classes&#8221;. I altered the argument simply for the sake of brevity in discussion &mdash; I will tie it back to Scala code examples at the end.</p>
<p>Let us assume we get rid of just one Haskell type-class, <code>Monad</code>. A monad is a <em>useful</em> abstraction, so we would certainly have to represent it (if you don&#8217;t believe this, then it is almost certain that <a href="http://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/sigfpe.blogspot.com');">you have reinvented monads inadvertently</a>). We might do this as follows:</p>
<pre>
{-# LANGUAGE RankNTypes #-}

data Monad' m = Monad' {
  unit :: (forall a. a -> m a),
  bind :: (forall a b. m a -> (a -> m b) -> m b)
}
</pre>
<p>Then, when it comes to instances, we would write:</p>
<pre>
listMonad = Monad' (return :: a -> [a]) (>>=)
maybeMonad = Monad' (return :: a -> Maybe a) (>>=)
</pre>
<p>Now when we wish to write the all-important functions over monads, we have to do the following:</p>
<pre>
sequence' monad [] = unit monad []
sequence' monad (x:xs) = let (>>>=) = bind monad in x >>>= y -> sequence' monad xs >>>= ys -> unit monad (y:ys)

mapM' monad f as = ... etc. etc.
</pre>
<p>The proposal by my opponent in the discussion is that we now write a version of each monad function for each instance by partially applying the monad instance. This is very cumbersome and importantly, <em>less useful</em>.</p>
<pre>
listSequence = sequence' listMonad
maybeSequence = sequence' maybeMonad

listMapM = mapM' listMonad
... and so on.
</pre>
<p>This creates what would otherwise be code in the order of O(1) to turn into O(n) code! This is not good. Do we get any benefit? No, there is no benefit, other than, in the case of Scala, appeasement of &#8216;the irrational squad&#8217; i.e. those fervently offended by the suggestion to divorce imperative programming. Let us just address this irrationality, even if just briefly, so we can move on.</p>
<p>Unlike Scala, Haskell&#8217;s side-effects are controlled, so the mind-shift is <em>forced</em> by the compiler (a successful form of counselling?). A Scala implicit function <em>can</em> perform side-effects. This would be very bad; if they were controlled, would these irrational objections be raised? The answer is no and it is quite easy to expose.</p>
<p>A claim to the contrary is often a case of <a href="http://en.wikipedia.org/wiki/Doublethink" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">doublethink</a>. Java is a programming language that deliberately encourages side-effects and by implication (also, by its poor type system), makes abstraction and composition extremely difficult to the point of impossibility very early on (see <a href="http://functionaljava.org/" onclick="javascript:pageTracker._trackPageview('/outbound/article/functionaljava.org');">Functional Java</a> for evidence). Yet even in this language &mdash; perhaps the most contrived available &mdash; we find implicit conversions that attract no objections whatsoever!</p>
<p>Imagine this Java signature <code>int toInt(char c)</code>. Such a user-defined function could indeed perform side-effects and any language feature permitting implicit use of this function is likely to attract criticism. Yet, this is one example of such a function built right-in to the Java language, which is <em>guaranteed by the language specification</em> to perform no side-effects. It is the fact that it is internalised by the user to perform no side-effects that makes it acceptable.</p>
<p>This is valid Java:</p>
<pre>
int i = c; // where c is of type char
</pre>
<p>I don&#8217;t wish to labour this point, other than to make it clear how easy it is to crush these irrationalities (it continues on in a usual uninteresting fashion).</p>
<p>Requiring code to blow out to O(n) from O(1) is itself not bad, but to further observe that there is no gain from it is conclusive. Interestingly, this is similar to a complaint by David MacIver (and myself &mdash; I am just less vocal about it) that Scala lacks default function argument lists in preference for overloading. This also creates unnecessary code-bloat (O(1) -> O(n)) for no benefit. (I hope I am not misrepresenting David here &mdash; I have lost the reference to his complaint).</p>
<p>Here is the equivalent Scala code to the above, however, Scala&#8217;s type system lacks the ability to pass the <code>unit</code> and <code>bind</code> functions &mdash; instead requiring the use of traits.</p>
<pre>
trait Unit[U[_]] {
  def unit[A](a: A): U[A]
}

trait Bind[M[_]] {
  def bind[A, B](ma: M[A], f: A => M[B]): M[B]
}

case class Monad[M[_]](u: Unit[M], b: Bind[M])

object Monad {
  val listMonad = Monad[List](new Unit[List] {
    def unit[A](a: A) = List(a) }, new Bind[List] {
    def bind[A, B](ma: List[A], f: A => List[B]) = ma flatMap f
  })

  def sequence[M[_], A](m: Monad[M], as: List[M[A]]): M[List[A]] = as match {
    case Nil => m.u.unit(Nil)
    case x :: xs => m.b.bind(x, (y: A) => m.b.bind(sequence[M, A](m, xs), (ys: List[A]) => m.u.unit(y::ys)))
  }

  def listSequence[A](as: List[List[A]]) = sequence[List, A](listMonad, as)
  def optionSequence[A](as: List[List[A]]) = sequence[Option, A](optionMonad, as)
  // etc. etc. O(n)!
}
</pre>
<p>As you can see, I was being <em>very</em> nice when I converted the argument to Haskell. The argument against such a proposal becomes even stronger in the context of Scala.</p>
<p>To my opponent, thanks for the discussion; it was fun and the intellectual maturity is admirable <img src='http://blog.tmorris.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tmorris.net/implicits-for-the-fearless/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Applicative Functor laws using Reductio (Scala)</title>
		<link>http://blog.tmorris.net/applicative-functor-laws-using-reductio-scala/</link>
		<comments>http://blog.tmorris.net/applicative-functor-laws-using-reductio-scala/#comments</comments>
		<pubDate>Thu, 03 Jul 2008 06:42:55 +0000</pubDate>
		<dc:creator>Tony Morris</dc:creator>
		
		<category>Programming</category>

		<guid isPermaLink="false">http://blog.tmorris.net/applicative-functor-laws-using-reductio-scala/</guid>
		<description><![CDATA[Here is the Applicative functor type-class (see Applicative Programming with Effects, Conor McBride, Ross Paterson):

class Applicative f where
  pure :: a -> f a
  () :: f (a -> b) -> f a -> f b

Here are the laws for the Applicative functor type-class:

identity pure id  u == u
composition pure (.)  [...]]]></description>
			<content:encoded><![CDATA[<p>Here is the <code>Applicative</code> functor type-class (<em>see <a href="http://www.soi.city.ac.uk/~ross/papers/Applicative.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.soi.city.ac.uk');">Applicative Programming with Effects</a>, Conor McBride, Ross Paterson</em>):</p>
<pre>
class Applicative f where
  pure :: a -> f a
  (<*>) :: f (a -> b) -> f a -> f b
</pre>
<p>Here are the laws for the Applicative functor type-class:</p>
<ul>
<li>identity<br/> <code>pure id <*> u == u</code></li>
<li>composition<br/> <code>pure (.) <*> u <*> v <*> w == u <*> (v <*> w)</code></li>
<li>homomorphism<br/> <code>pure f <*> pure x == pure (f x)</code></li>
<li>interchange<br/> <code>u <*> pure x == pure (\f -> f x) <*> u</code></li>
</ul>
<p>Here are those laws stated using <a href="http://reductiotest.org/" onclick="javascript:pageTracker._trackPageview('/outbound/article/reductiotest.org');">Reductio</a>. I have changed <code>pure</code> to <code>unit</code> and the language is Scala:</p>
<pre>

object ApplicativeLaws {
  def identity[A[_], X](implicit a: Applicative[A],
                                 aax: Arbitrary[A[X]],
                                 e: Equal[A[X]]) =
    prop((apx: A[X]) => apx === a(a.unit((x: X) => x), apx))

  def composition[A[_], X, Y, Z](implicit a: Applicative[A],
                                aayz: Arbitrary[A[Y => Z]],
                                aaxy: Arbitrary[A[X => Y]],
                                aax: Arbitrary[A[X]],
                                e: Equal[A[Z]]) =
    prop((apyz: A[Y => Z], apxy: A[X => Y], apx: A[X]) =>
            a(apyz, a(apxy, apx)) ===
            a(a(a(a.unit((f: Y => Z) => (g: X => Y) => f compose g), apyz), apxy), apx))

  def homomorphism[A[_], X, Y](implicit a: Applicative[A],
                                        ax: Arbitrary[X],
                                        axy: Arbitrary[X => Y],
                                        e: Equal[A[Y]]) =
    prop((f: X => Y, x: X) => a(a.unit(f), a.unit(x)) === a.unit(f(x)))

  def interchange[A[_], X, Y](implicit a: Applicative[A],
                                       ax: Arbitrary[X],
                                       apxy: Arbitrary[A[X => Y]],
                                       e: Equal[A[Y]]) =
    prop((f: A[X => Y], x: X) =>
      a(f, a.unit(x)) === a(a.unit((f: X => Y) => f(x)), f))
}
</pre>
<p>Pretty neat eh? <img src='http://blog.tmorris.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Let&#8217;s test the <code>Applicative</code> instance for <code>List</code>:</p>
<pre>
List(identity[List, Int],
     composition[List, Int, Long, String],
     homomorphism[List, Int, String],
     interchange[List, Int, String]).
  foreach(p => summary println p)
</pre>
<p>This runs 100 unit tests per property, so 400 unit tests altogether. Here is the output:</p>
<pre>
OK, passed 100 tests.
OK, passed 100 tests.
OK, passed 100 tests.
OK, passed 100 tests.
</pre>
<p>Woot woot!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tmorris.net/applicative-functor-laws-using-reductio-scala/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Just what the funk is a Functor anyway?</title>
		<link>http://blog.tmorris.net/just-what-the-funk-is-a-functor-anyway/</link>
		<comments>http://blog.tmorris.net/just-what-the-funk-is-a-functor-anyway/#comments</comments>
		<pubDate>Sat, 28 Jun 2008 08:28:15 +0000</pubDate>
		<dc:creator>Tony Morris</dc:creator>
		
		<category>Programming</category>

		<guid isPermaLink="false">http://blog.tmorris.net/just-what-the-funk-is-a-functor-anyway/</guid>
		<description><![CDATA[Runar recently made mention of these so-called Functors and Monads in his excellent post about concurrency/actors in Java. There are all sorts of tutorials out there for understanding what a Monad is, however, I am of the opinion that one must first understand what a Functor is. This is because it is less complex and [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://apocalisp.wordpress.com/" onclick="javascript:pageTracker._trackPageview('/outbound/article/apocalisp.wordpress.com');">Runar</a> recently made mention of these so-called Functors and Monads in <a href="http://apocalisp.wordpress.com/2008/06/18/parallel-strategies-and-the-callable-monad/" onclick="javascript:pageTracker._trackPageview('/outbound/article/apocalisp.wordpress.com');">his excellent post about concurrency/actors in Java</a>. There are all sorts of tutorials out there for understanding what a Monad is, however, I am of the opinion that one must first understand what a Functor is. This is because it is less complex and more general (all monads are functors plus more).</p>
<p>The Java Posse also made a couple of false claims about Runar&#8217;s article, but one in particular needs addressing. This is the notion that a functor is applicable to &#8220;Functional Programming&#8221;. This is false. A functor is applicable to <em>programming</em>. You really, really need to understand what a functor is, if you&#8217;re ever going to be skilled in <em>any type of</em> programming; even if it&#8217;s just Java web applications for the rest of your life. This concept does not exist &#8216;on the other side of the fence&#8217; in the imaginary &#8216;functional programming world&#8217;. These suggestions are understandable of course and I don&#8217;t intend to labour the point &mdash; only make this point clear, since these apparent divides seem to pop up often. On with the story&#8230;</p>
<p>In Java, we have an interface called <code><a href="http://java.sun.com/javase/6/docs/api/java/lang/CharSequence.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/java.sun.com');">CharSequence</a></code>. A few things can be said about <code>CharSequence</code>. How about:</p>
<blockquote><p>
All implementations guarantee that for some integer <code>n</code>, then if <code>n >= 0 &#038;&#038; n < length()</code>, then <code>charAt(n)</code> will not throw an exception.
</p></blockquote>
<p>We might call this a <em>law</em> about <code>CharSequence</code> that all implementations must satisfy. We could even find other laws that must satisfy about implementations of the <code>CharSequence</code> interface.</p>
<p>A Functor is an interface and it has two laws. Sadly though, this interface cannot be expressed using Java&#8217;s type system &mdash; it is simply not clever enough. We must use a hypothetical Java to express it. First though, we have to make up for Java&#8217;s missing first-class functions by using an interface. This is easy:</p>
<pre>
interface Function&lt;A, B&gt; {
  B f(A a);
}
</pre>
<p>OK, so this a just an interface like any others. It needn&#8217;t satisfy any laws; it just takes an argument (A) and returns (B). We could write bazillions of implementations of this interface in Java. We&#8217;re going to need this interface to write the <code>Functor</code> interface.</p>
<p>Now, the missing part of Java is called <em>higher-kinds</em> &mdash; a term you needn&#8217;t concern yourself with too much. I hope this hypothetical syntax is enough to make the point clear:</p>
<pre>
interface Functor&lt;E&lt;_&gt;&gt; {
  &lt;A, B&gt; E&lt;B&gt; fmap(Function&lt;A, B&gt; f, E&lt;A&gt; fa);
}
</pre>
<p>So the foreign part here is <code>E&lt;_&gt;</code>. Consider E to stand for &#8216;Environment&#8217;. It is a type parameter that takes yet another type parameter (which is why it is denoted E&lt;_&gt;). This means I could use <code>List</code> or <code>Set</code>, but not <code>Integer</code> as the type parameter value for E, since <code>List</code> and <code>Set</code> take another type parameter while <code>Integer</code> does not. You might think of the <code>Functor</code> interface as &#8216;applying the given function within the environment&#8217;.</p>
<p>We might write an implementation like this:</p>
<pre>
class ListFunctor implements Functor&lt;List&gt; {
  public &lt;A, B&gt; List&lt;B&gt; fmap(Function&lt;A, B&gt; f, List&lt;A&gt; list) {
    // todo: apply the given function on all elements in 'list' and return the result
  }
}
</pre>
<p>In general discussion, we would call this <em>the list functor</em>, simply because the value for the environment has been applied. In Runar&#8217;s article, he was talking about the <code>Callable</code> functor; yet another environment. There are many possibilities for the environment here; <code>List</code> and <code>Callable</code> are but two.</p>
<h4>The Laws</h4>
<p>Let us not forget the laws <img src='http://blog.tmorris.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Just like all implementations of <code>CharSequence</code> have laws to obey, so do all functors. They are called <em>identity</em> and <em>composition</em>. </p>
<h5>Identity</h5>
<p>Remember the <code>Function</code> interface? Here is an implementation:</p>
<pre>
class Identity&lt;A&gt; implements Function&lt;A, A&gt; {
  public A f(A a) { return a; }
}
</pre>
<p>If we are given an implementation of <code>Functor</code> &mdash; which I will call <code>f</code> &mdash; then it must satisfy <code>f.fmap(new Identity&lt;T&gt;(), x)</code> is equivalent to <code>x</code> <em>(for any value of x)</em>. So that&#8217;s the identity law out of the way. Mapping <em>the identity function</em> across a functor yields the same value.</p>
<h5>Composition</h5>
<p>The law of composition is a little less friendly when it comes to expressing it in Java so I will refrain <img src='http://blog.tmorris.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  While it is an important part of making up the concept of a functor, it may be best to defer this final piece of the puzzle for now.</p>
<p>For completeness, I will state the law using a shorter syntax, but if this is foreign or worrying, then please ignore it: <code>f.fmap(a compose b, x)</code> is equivalent to <code>f.fmap(a, f.fmap(b, x))</code> <em>(for any value of a, b and x &mdash; a and b are <code>Function</code> objects)</em>.</p>
<p>That&#8217;s all there is to a Functor. If you use the <code>map</code> function on lists or perhaps the <code>map</code> method on <code>scala.Option</code>, then you are using one specific instance of a functor, since these functions/methods satisfy the conditions for a functor. Even throwing an exception is using a specific functor! Perhaps that can be explained another time <img src='http://blog.tmorris.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I should also add that when referring to a functor (unqualified), we are referring to a <em>covariant</em> functor. Other types of functors include contra-variant and invariant functors. We can talk about those another day <img src='http://blog.tmorris.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>Next: Just What the Flip is a Monad?</p>
<p>Questions?
</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tmorris.net/just-what-the-funk-is-a-functor-anyway/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Monad Laws using Reductio (Scala)</title>
		<link>http://blog.tmorris.net/monad-laws-using-reductio-scala/</link>
		<comments>http://blog.tmorris.net/monad-laws-using-reductio-scala/#comments</comments>
		<pubDate>Thu, 26 Jun 2008 00:57:10 +0000</pubDate>
		<dc:creator>Tony Morris</dc:creator>
		
		<category>Programming</category>

		<guid isPermaLink="false">http://blog.tmorris.net/monad-laws-using-reductio-scala/</guid>
		<description><![CDATA[In the spirit of yesterday&#8217;s post that denoted the Functor Laws using Reductio, I will also give the Monad Laws. Before I do however, here is an example use of the FunctorLaws object that runs 600 unit tests when testing a Functor implementation for scala.Option[A], scala.List and finally, for the scala.Either[A, _] functor just to [...]]]></description>
			<content:encoded><![CDATA[<p>In the spirit of yesterday&#8217;s post that denoted the Functor Laws using Reductio, I will also give the Monad Laws. Before I do however, here is an example use of the <code>FunctorLaws</code> object that runs 600 unit tests when testing a <code>Functor</code> implementation for <code>scala.Option[A]</code>, <code>scala.List</code> and finally, for the <code>scala.Either[A, _]</code> functor just to make it a bit quirky and probably confuse a few of you (in that case, ignore it for now!) <img src='http://blog.tmorris.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre>
  val prop_OptionIdentity = identity[Option, Int]
  val prop_OptionComposition = composition[Option, Int, String, Long]

  val prop_ListIdentity = identity[List, Int]
  val prop_ListComposition = composition[List, Int, String, Long]

  val prop_EitherIdentity = identity[Apply1Of2[Either, String]#Apply, Int]
  val prop_EitherComposition = composition[Apply1Of2[Either, String]#Apply, Int, String, Long]

  // OK passed 100 tests. (appears 6 times &mdash; once per property)
</pre>
<p>&#8230;and the obligatory Monad Laws follow (import statements omitted this time, but they are the same as previous)&#8230;</p>
<pre>
object MonadLaws {
  def leftIdentity[M[_], A, B](implicit m: Monad[M],
                                     am: Arbitrary[M[B]],
                                     aa: Arbitrary[A],
                                     ca: Coarbitrary[A]) =
    prop((a: A, f: A => M[B]) =>
      m.bind(f, m.unit(a)) === f(a))

  def rightIdentity[M[_], A](implicit m: Monad[M],
                                      am: Arbitrary[M[A]]) =
    prop((ma: M[A]) => m.bind((a: A) =>
      m.unit(a), ma) === ma)

  def associativity[M[_], A, B, C](implicit m: Monad[M],
                                           am: Arbitrary[M[A]],
                                           ca: Coarbitrary[A],
                                           cb: Coarbitrary[B],
                                           amb: Arbitrary[M[B]],
                                           amc: Arbitrary[M[C]]) =
    prop((ma: M[A], f: A => M[B], g: B => M[C]) =>
      m.bind(g, m.bind(f, ma)) === m.bind((a: A) => m.bind(g, f(a)), ma))
}
</pre>
<p>Woot! Woot!
</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tmorris.net/monad-laws-using-reductio-scala/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Functor Laws using Reductio (Scala)</title>
		<link>http://blog.tmorris.net/functor-laws-using-reductio-scala/</link>
		<comments>http://blog.tmorris.net/functor-laws-using-reductio-scala/#comments</comments>
		<pubDate>Wed, 25 Jun 2008 06:07:08 +0000</pubDate>
		<dc:creator>Tony Morris</dc:creator>
		
		<category>Programming</category>

		<guid isPermaLink="false">http://blog.tmorris.net/functor-laws-using-reductio-scala/</guid>
		<description><![CDATA[A somewhat intricate and extremely useful code snippet using Reductio for testing the laws of any Functor instance (note that the Functor type is part of Scalaz):

import reductios.Property._
import reductios.Arbitrary
import reductio.Coarbitrary
import reductios.Arbitrary._

object FunctorLaws {
  def identity[F[_], A](implicit f: Functor[F], af: Arbitrary[F[A]]) =
    prop((fa: F[A]) => f.fmap((a: A) => a, fa) === fa)

 [...]]]></description>
			<content:encoded><![CDATA[<p>A somewhat intricate and extremely useful code snippet using <a href="http://reductiotest.org/" onclick="javascript:pageTracker._trackPageview('/outbound/article/reductiotest.org');">Reductio</a> for testing the laws of any Functor instance (note that the <code>Functor</code> type is part of <a href="http://wiki.workingmouse.com/index.php/Scalaz" onclick="javascript:pageTracker._trackPageview('/outbound/article/wiki.workingmouse.com');">Scalaz</a>):</p>
<pre>
import reductios.Property._
import reductios.Arbitrary
import reductio.Coarbitrary
import reductios.Arbitrary._

object FunctorLaws {
  def identity[F[_], A](implicit f: Functor[F], af: Arbitrary[F[A]]) =
    prop((fa: F[A]) => f.fmap((a: A) => a, fa) === fa)

  def composition[F[_], A, B, C](implicit f: Functor[F],
                                          af: Arbitrary[F[A]],
                                          ac: Arbitrary[C],
                                          cb: Coarbitrary[B],
                                          ab: Arbitrary[B],
                                          ca: Coarbitrary[A]) =
    prop((fa: F[A], h: B => C, i: A => B) =>
            f.fmap(h compose i, fa) === f.fmap(h, f.fmap(i, fa)))
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.tmorris.net/functor-laws-using-reductio-scala/feed/</wfw:commentRss>
		</item>
		<item>
		<title>You&#8217;d naturally write flatMap yourself if asked the question</title>
		<link>http://blog.tmorris.net/youd-naturally-write-flatmap-yourself-if-asked-the-question/</link>
		<comments>http://blog.tmorris.net/youd-naturally-write-flatmap-yourself-if-asked-the-question/#comments</comments>
		<pubDate>Wed, 25 Jun 2008 00:04:45 +0000</pubDate>
		<dc:creator>Tony Morris</dc:creator>
		
		<category>Programming</category>

		<guid isPermaLink="false">http://blog.tmorris.net/youd-naturally-write-flatmap-yourself-if-asked-the-question/</guid>
		<description><![CDATA[Many people struggle to understand those fluffy things called Monads and why they are important. I&#8217;m not going to attempt to alleviate this to a large degree, but I have had a recent success with a friend in having them attempt to write a familiar Scala function as a method. That is, the List.flatten function, [...]]]></description>
			<content:encoded><![CDATA[<p>Many people struggle to understand those fluffy things called <em>Monads</em> and why they are important. I&#8217;m not going to attempt to alleviate this to a large degree, but I have had a recent success with a friend in having them attempt to write a familiar Scala function as a method. That is, the <code><a href="http://www.scala-lang.org/docu/files/api/scala/List$object.html#flatten(List[List[A]])" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.scala-lang.org');">List.flatten</a></code> function, which simply takes a <code>List</code> of <code>List</code> of some type <code>A</code> and returns a <code>List[A]</code>. It does this by concatenating all the lists together. I think most people are familiar with this function and have a good mental model of how it works. If this is the case and you are less confident about <code>List.flatMap</code>, then I hope to bring a point to your attention that might help you bring it home.</p>
<p>If you take a look at <code>List.sort</code>, you see it takes a function <code>(A, A) => Boolean</code>. This is because the type parameter to <code>List</code> is &#8216;just any A&#8217;. It would be nice if it was &#8216;any A, so long as it has defined order&#8217;. That way, you can just call <code>list.sort</code> and be done with it. This would require the creation of a new class with a more restricted type parameter; for example, you might pass the function at list creation time, like you do with a <code>TreeMap</code>.</p>
<p>Imagine writing <code>List.flatten</code> on the <code>List[A]</code> class as a <em>method</em> using the same technique. You wouldn&#8217;t be able to, since the method belongs on a <code>List[List[A]]</code>. You&#8217;d need to write the method such that it takes an argument: <code>A => List[A]</code> before you could then call <code>flatten</code>. When you have a <code>List[List[A]]</code>, you&#8217;d just call this method with the identity function <code>x => x</code> to obtain your resulting <code>List[A]</code>. Here is how the method would look:</p>
<pre>
def flatten(f: A => List[A]): List[A] = ...
</pre>
<p>Guess what?! This method is <code>flatMap</code>! Let&#8217;s ignore the fact that the Scala API is significantly broken, including the <code>List.flatMap</code> method using <code>Iterable</code> in place of <code>List</code> here. Notice though, that <code>flatMap</code> is actually generalised by taking another type parameter, so we have just invented an unnecessarily specialised version of <code>flatMap</code>. Let&#8217;s fix it:</p>
<pre>
def flatten[B](f: A => List[B]): List[B] = ...
</pre>
<p>Woot woot! In other words, <code>flatten(list)</code> is equivalent to <code>list flatMap (x => x)</code>. Furthermore, this should hold for more than just list, but for other type constructors too (sadly, <code>Option</code> is missing a flatten function: <code>Option[Option[A]] => Option[A]</code>). This is a special relationship that all monads have (join is a synonym for flatten and bind is a synonym for flatMap):</p>
<blockquote><p>
join = bind id
</p></blockquote>
<p>We can express this using <a href="http://reductiotest.org/" onclick="javascript:pageTracker._trackPageview('/outbound/article/reductiotest.org');">Reductio</a> (the Scala API of course!):</p>
<pre>
val prop_flat = prop((t: List[List[Int]]) => List.flatten(t) == t.flatMap(x => x))
// OK passed 100 tests.
</pre>
<p>I hope this helps. If it doesn&#8217;t, ask a question or ignore my ranting <img src='http://blog.tmorris.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tmorris.net/youd-naturally-write-flatmap-yourself-if-asked-the-question/feed/</wfw:commentRss>
		</item>
		<item>
		<title>ABC Learning Centres required for adults</title>
		<link>http://blog.tmorris.net/abc-learning-centres-required-for-adults/</link>
		<comments>http://blog.tmorris.net/abc-learning-centres-required-for-adults/#comments</comments>
		<pubDate>Mon, 23 Jun 2008 05:05:32 +0000</pubDate>
		<dc:creator>Tony Morris</dc:creator>
		
		<category>General</category>

		<guid isPermaLink="false">http://blog.tmorris.net/abc-learning-centres-required-for-adults/</guid>
		<description><![CDATA[From http://www.news.com.au/comments/0,23600,23907216-462,00.html on the recent price rise by ABC Learning Centres (i.e. child care):

ABC Learing centres have now increased there fees three times since early 2007. There justification for these raises in no way benefit the children in they&#8217;re care or they&#8217;re staff!.

]]></description>
			<content:encoded><![CDATA[<p>From <a href="http://www.news.com.au/comments/0,23600,23907216-462,00.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.news.com.au');">http://www.news.com.au/comments/0,23600,23907216-462,00.html</a> on the recent price rise by ABC Learning Centres (i.e. child care):</p>
<blockquote><p>
ABC Learing centres have now increased there fees three times since early 2007. There justification for these raises in no way benefit the children in they&#8217;re care or they&#8217;re staff!.
</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://blog.tmorris.net/abc-learning-centres-required-for-adults/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
