Wednesday, October 15, 2008

Some thoughts on Turtle Graphics Basics

In the comments of last turtle post, Joel pointed out a way to get commands composable. I didn't quite get it to work, probably because of that Command is a type synonym and not a concrete type. The first time I saw the proposed solution, to combine commands with <|>, I got a little afraid. I'll explain why..

<Update>

Joel pointed out (in a mail) that Haskell98 doesn't permit instances of type synonyms or lists of types. If the flag "fglasgow-exts" is used, then the problem is solved.

</Update>

The biggest reason I got afraid was that it is still up to the consumer of the code to combine commands in a "good" way, i.e., to log intermediate positions. But, It would be perfectly legal to combine commands with (.) instead of (<|>), making the API quite risky. I now think a bit different..

It would be possible to kind of wrap the commands into a data structure of their own (as the Command pattern in OO):

> data C = C { unC :: Command }

In some way, this is very type-safe, since it will be cumbersome to un-wrap the commands to combine them in a "bad" way..

> go2 = C { (unC go) . (unC go) }

..thus, users are forced to use our special operator for combining commands. But there something I don't like about this. We're kind of forcing the users into a datastructure, just to restrict them. I think we loose a lot of nice functions (i.e. from the prelude) this way. Of course, we could define functions that makes it easier for the user, but the user still has to learn those functions. What I'm trying to say is that it sometimes is bad to invent a whole new API style from scratch, when for example a monadic style API has the benefit that more people know about it and that we can "piggyback" on all the tutorials on monads. Or maybe it's just me that is too focused on monads at the moment. ;)

I guess this could be a nice discussion? What do you think?

Right now, my biggest reason to be afraid of Joels solution is that it uses type classes, which is a very exotic feature, compared to other functional languages. There are obviously nice, but it would be hard to see how a "nice" Turtle Graphics API could be ported to i.e. F#, if we based the API on type classes.

Next: Changing interface on primitive commands

Tuesday, October 14, 2008

Joining Dotway!

Last Friday I joined Dotway! Dotway is a .NET consulting company and was founded in Malmö, but I will be working in the Gothenburg office.

Dotway is a Microsoft Gold partner (achieved through competencies) and offers services such as software development, design support, and training/mentoring. Dotway also practices agile and TDD, and "Dotway consultants are Certified ScrumMasters".

I will start working in the beginning of November. Very exciting!

Some links:
Dotway
Mikael Freidlitz
Johan Normén
Magnus Mårtensson
Øredev (a conference and a sister company)

Monday, October 13, 2008

Turtle Graphics Basics

Some weeks ago, I watched Don't fear the Monads, again. Beckman said something like "there nothing about monads that you don't already know" and "after some time, you'd be inventing monads yourself, but you probably wouldn't know that they were monads". Beckman inspired me to start a small (!) project on Turtle Graphics blog posts.

The idea is to write a very small piece of Haskell code in each post, where every post is a Turtle Graphics implementation. Or, not implementation, but rather just a model, so no real graphics. You can see them as small Turtle Graphics APIs, that focus entirerly on the data and not anything about presenting the data.

Now, not every API is an internal DSL, but for these posts I'll try to put on my language sun-glasses..

First we need a definition of a Turtle:
> data Turtle = Turtle {
> x :: Double,
> y :: Double,
> alpha :: Double -- alpha = 0 means East
> }
> deriving (Show)
The first idea (the trivial/naïve implementation) is to define functions with the type signatures Turtle -> Turtle. The functions I have in mind is go, left, right, and rotate, hopefully all self-explanatory. Let's do a type synonym, because it's fun:

> type Command = Turtle -> Turtle

Here are the commands, very basic:
> go, left, right :: Command
> go t = t { x = x t + step * cos (alpha t),
> y = y t + step * sin (alpha t),
> alpha = alpha t }

> left t = t { alpha = alpha t + pi/2 }
> right t = t { alpha = alpha t - pi/2 }

> rotate :: Double -> Command
> rotate v t = t { alpha = alpha t + v }

> step = 1
Note that rotate has a different type. Also note the order of the arguments: we can use currying so that if we give rotate just one argument (an angle), we will get a Command.

Let us just see what the user code looks like:

*Main> let t = Turtle {x = 1, y = 1, alpha = 0}
*Main> t
Turtle {x = 1.0, y = 1.0, alpha = 0.0}

*Main> go t
Turtle {x = 2.0, y = 1.0, alpha = 0.0}

We can combine functions with the operator (.)

*Main> (go . go) t
Turtle {x = 3.0, y = 1.0, alpha = 0.0}

And, of course, we can define new functions in terms of the basic ones:

*Main> let go2 = go . go
*Main> go2 t
Turtle {x = 3.0, y = 1.0, alpha = 0.0}

The presentation is a bit rough, especially for non-zero angles..

*Main> right t
Turtle {x = 1.0, y = 1.0, alpha = -1.5707963267948966}

..but I assume you can calculate from radians to degrees in your head.. ;)

As you might have seen, the ordering of arguments for rotate was important:

*Main> (go . (rotate pi) . go) t
Turtle {x = 1.0, y = 1.0000000000000002, alpha = 3.141592653589793}

If the ordering of arguments were different, the above would not have been possible to write. Instead we would have been forced to write a lambda-expression, which is maybe not the best example of a good user code (if you can avoid it, at least).

Note that we also can remove the definitions of left and right, and replace them with

> left' = rotate (pi/2)
> right' = rotate (-pi/2)

Now, a nice feature would be to let a user give a list of Commands and a Turtle to a function, returning the final position:

> runR :: [Command] -> Turtle -> Turtle
> runR [] t = t
> runR (c:cs) t = runR cs (c t)

Here's where I think it can be useful to know something about functions is general. For example, functions with type a -> a forms a monoid [1,2] together with the operator (.) and identity id. This allows us to write runR in a more readable form (now called run):

> run :: [Command] -> Turtle -> Turtle
> run cs t = (foldr (.) id cs) t

A monoid is a nice thing to be, but what is really the purpose with the run function? Isn't the whole goal with a "Turtle Graphics" that we compute a list of positions, so that we can plot them somewhere? It's no use just to calculate a final position: the picture will become pretty boring eventually.. ;)

What we need is a function that takes a list of commands and a start position, returning a list of positions:

> runHistory :: [Command] -> Turtle -> [Turtle]

We make runHistory a wrapper function around runToList:

> runHistory cs t = runToList cs [t]

> runToList :: [Command] -> [Turtle] -> [Turtle]
> runToList [] ts = ts
> runToList _ [] = []
> runToList (c:cs) (t:ts) = runToList cs ((c t) : t : ts)

<Update>

Joel pointed out (in the comments) that runHistory could be written as:

> runHistory = flip (scanr ($)) . reverse

It's of course a lot better than my definition(s), from a readable code perspective. I imagine that my version is more performant (since I do not reverse), but as we all know, performance only matters until you notice the problem (as I pointed out in the comments myself). So, I fell into the trap of pre-optimizing.. Oh my, oh my.

</Update>

Let's try it out:

*Main> runHistory [go,right,rotate pi, go,go] t
[Turtle {x = 2.0, y = 3.0, alpha = 1.5707963267948966},Turtle {x = 2.0, y = 2.0, alpha = 1.5707963267948966},Turtle {x = 2.0, y = 1.0, alpha = 1.5707963267948966},Turtle {x = 2.0, y = 1.0, alpha = -1.5707963267948966},Turtle {x = 2.0, y = 1.0, alpha = 0.0},Turtle {x = 1.0, y = 1.0, alpha = 0.0}]

Hmm, the presentation gets real ugly. Perhaps an implementation of (Show) would be nice, but that's out of scope for this post.

I think there's some smelly code here. We have "bolted on" a history feature on top of the basic commands, so the only knowledge of a history (or log) is in runHistory itself. From a logging perspective, the basic functions do not compose at all! Let me show you what I mean..

Suppose we define a go2 in terms of go (see above). Clearly, we would like go2 to write to the log twice. With the current implementation, this is impossible! There's no way that runHistory can write more than one time to the log, per command. Well, it could be done, but it's not pretty:

*Main> let go2 = [go,go]
(*Main> let prog = [go,go2,go] -- type error)
*Main> let prog = [[go],go2,[go]]
*Main> runHistory (concat prog) t

Even uglier:

*Main> let go3 = [go2,[go]]
(*Main> let prog = [[go],go3,[go]] -- type error)
*Main> let prog = [[[go]],go3,[[go]]]
*Main> runHistory (concat (concat prog)) t

From this, it's obvious that we need to let the basic functions be aware of history/logging. That would be the goal of future posts.


Comment/spoiler: Kenn Knowles has also written a blog post on a Turtle Graphics implementation. Though, the aim of my post(s) is to start out real basic and then evolve the code through several posts. Basically, Kenn's implementation is a "state-over-writer" monad transformer, with a self-implemented difference list as the writer monoid.

Wednesday, October 8, 2008

Better DI

I was watching "InfoQ: Mock Roles Not Object States" with Nat Pryce and Steve Freeman yesterday. I had read the paper previous to watching the video, and I pretty much expected the same content but in a different form. Boy was I wrong..

In particular, they talked a few minutes on an argument against Dependency Injection (DI), namely that the constructor gets lots and lots of arguments. I used DI the first time a couple of weeks ago, so I'm pretty new to it, and I wasn't sure I was doing exactly the right thing. And, yes, the constructors at some places became huge.

What the InfoQ presentation thought me was that not all interfaces a class use are dependencies per se. Classes can for example be equipped with default parts or policies, that can be changed after creation. The important thing is that the instance will work anyway, which is not the case if an instance is missing out a dependency.

This nice picture (screenshot from their slides) made it click for me:



Big thanks to Johan Normén who mentioned the paper on the SweNug meeting two weeks ago!

Tuesday, September 23, 2008

A thought on F#

A while ago I read this blogpost by Phil Wadler. The post is a comment on an article from an issue of Journal of Functional Programming. In that, Yaron Minsky and Stephen Weeks from Jane Street Capital talks about their experiences with functional programming on Wall Street. Wadler quotes from the article:
When we first tried switching over from VB to C#, one of the most disturbing features of the language for the partners who read the code was inheritance. They found it difficult to figure out which implementation of a given method was being invoked from a given call point, and therefore, difficult to reason about the code. It is worth mentioning that OCaml actually does support inheritance as part of its object system. That said, objects are an obscure part of the language, and inheritance even more so. At Jane Street, we almost never use objects and never use inheritance. We use standard functional programming techniques and code reviewers find that style more comprehensible. In particular, they can reason by following static properties of the code (module boundaries and functor applications) rather than dynamic properties (what class an object is).

This made me think of F#, which is inspired by OCaml. Will users of F# tend to not use any OO, just as in Jane Street Capital? Or, put in another way, will F# users tend to only be consumers of OO code (i.e., the .NET framework) and provide a "nice" OO-style API for client code, but "underneath the surface" focus entirerly on the functional part of F#?

Media: Wadler does a funny thing, in the very last minute of his talk (Faith, Evolution, and Programming Languages).

Attending events

Tomorrow I will attend SweNug Gbg for the first time. Exciting! I had a real good time at the open space (in Gothenburg) one month ago and I'm hoping that tomorrow will be fun as well. But it's not without sacrifices: I'll have to catch the earliest train to Ystad (@ 05.40) to attend a driving lesson on Thursday.

On 3 October, I will attend Microsofts half-day on data access, in Malmö, where Erik Meijer and Jimmy Nilsson will talk. Erik Meijer is one of the (many) reasons that I chose to focus on .NET rather than Java. After you read this post, go and read all his papers! :)

A funny quote from the event page:
[...] in the first half of the last century, mathematicians invented monads, which have subsequently migrated to the computer science mainstream via functional programming (mainly Haskell) and have recently shown up as LINQ in C# 3.0 and Visual Basic.
Jimmy Nilsson is the author of Applying Domain-Driven Design and Patterns, which I read this summer, great book! And, by the way, Jimmy is the second best developer in Sweden (rated by ComputerSweden).

Finally, a note-to-self: try to write shorter posts and more often.

Saturday, September 6, 2008

ClickOnce deployment or not?

Some weeks ago, I developed a small program in C# called P4 Explorer. To distribute it, i used a technique called ClickOnce deployment, which is a part of Visual Studio C# Express 2008. This blog post will be about what ClickOnce deployments are, how they can be used, and why you in the end shouldn't use them...

ClickOnce
ClickOnce deployments will simplify your deployment a lot. To deploy your application, all you need to do is:
  1. specify the location to publish the application (i.e. a network drive, web site or ftp),
  2. specify from what location the users will install it from (propably the same as 1), and
  3. decide whether the application should be installed at the start menu, or always must be started from the install path (2).
Furhermore you can specify if the application automatically should check for updates, which is really great if you plan to update your application frequently. You then specify how often the it should check for updates, and when an update is found, the user will be notified and can download the latest version. All by only selecting "The application should check for updates". Very nice!

Now, for you to deploy a new version, all you do is click "Publish". When the user then starts the program, the update will be found and installed (if permitted by the user). Very easy!

Limitations
Application Path
ClickOnce deployment doesn't come for free though. First of, the application won't be installed under "C:\Program Files\MyCompany\MySoftware" as you might expect, but at some secret place (hidden from the user and developer). If you decide to let the installer add a shortcut to your start menu, there is no way to find out where this shortcut points, as it's not a normal shortcut. Right clicking on it and selecting properties will not give you the information you expect, i.e. the path to the executable.
Now, there is a simple way of finding out the path of the executable. When starting the installed application, the property Application.ExecutablePath will be correctly set and you can thus be used to, for example, add to the PATH environment variable:
void UpgradePathVariable()
{
string l_ApplicationFolder = Path.GetDirectoryName(Application.ExecutablePath);
string l_PathVariable = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
if (!l_PathVariable.Contains(l_ApplicationFolder))
{
l_PathVariable = l_OldPathVariable + ";" + l_ApplicationFolder;
}
Environment.SetEnvironmentVariable("PATH", l_PathVariable, EnvironmentVariableTarget.Machine);
}

Parameters
Also, because the program doesn't have a fixed installation path, there is no support for sending parameters to the program. I.e. args in static void Main(string[] args) will always be empty. The documentation at MSDN states that the only way to send parameters to a click once application is to deploy it at a web page, and let the user send html-parameters to it, i.e.:
http://www.yourdomain.com/yourapplication.exe?parameter1=val1&parameter2=val2
But
  1. this requires your application to be deployed using a web page, and
  2. you must always download the installer every time you need to sent parameters to the program.
Say for example you want to let the user start the program by right clicking on a file in explorer and selecting "Open in my program". You would need to add a line in your registry pointing to the executable file:

pathtoyourexe "%1"

This would be both slow and hacky if using the recommended http-style mentioned above. Instead, by using the Application.ExecutablePath property, you can actually access the physical path to the installed executable, and thus add this path to the registry. With this setup correctly, right clicking on a file and selecting your program to open it with, will open the program and send the parameter correctly to it!

Settings
But, even though everything might seem to work out fine, you will soon notice that the Settings object defined in your application will be different if starting the program using the shortcut from your start menu, or right clicking on a file. They are not sharing the same application settings. And if you upgrade the program, all settings in your "right clicked version" will be gone, because the new version will be installed in a new folder.

In the end
Even though click once applications are really easy to deploy, and give you a lot for free, the limitations just makes them really hard to work with. Making simple applications might work, but as soon as you want the user to interact with it through the explorer shell, you are better off making your own installer (or using a free one such as NSIS). So in the end I decided to deploy my program manually using a source control, which made all my problems go away. Sending parameters worked, settings worked, and the application had a fixed folder!

The only thing I was really missing from ClickOnce was the ability for the program to automatically check for updates, which was something I really needed to make sure everyone using my application had the latest version (hopefully having less bugs in it). But it turned out this wasn't so hard to make on my own! The pseudo code for it, printed here, is divided in two programs - your main application, yourapp.exe, and the upgrade application, upgrade.exe.

yourapp.exe:
  1. Is there a new version available (i.e. check using source control)
  2. Copy upgrade.exe (and dependencies) to a new folder "temp"
  3. Start new process temp\upgrade.exe
  4. Close program
upgrade.exe:
  1. Make sure all instances of yourapp.exe are closed
  2. Download the latest version (i.e. using source control)
  3. Start new process ..\yourapp.exe
  4. Close program
You can always make it faster by running the check for new version in it's own thread, and only checking every x hour, but the main thing is that I get the same features as if running with ClickOnce, but don't need to limit my application as much as you do with ClickOnce applications!

So, ClickOnce, good for small application, not good for more advanced applications.