Friday, 11 April 2014

Emacs: Racket on Windows

As a continuation from my last post, I also want to show how to install Racket on Emacs for Windows.

I'm going to show the easiest way (that I know of).  So, this will not install the most recent version of Emacs, but will be the quickest and easiest way possible.

In order to install Emacs, I'm going to use Chocolatey.  Chocolatey is the budding Windows package manager based on NuGet.

So here we go!

Chocolatey (Powershell Install):
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin

Emacs (super text editor):
cinst emacs

Geiser (Racket support for emacs):

  • Find your .emacs file
    • Open emacs and find .emacs file by using:
      • C-x C-f ~/.emacs  (~/ is the current home directory)
  • Add package archive configuration to .emacs
    • Add this to the .emacs file:
      (require 'package)
      (add-to-list 'package-archives
        '("marmalade" . "http://marmalade-repo.org/packages/"))
      ;; You don't need this one if you prefer marmalade and released versions:
      ;; (add-to-list 'package-archives
      ;;  '("melpa" . "http://melpa.milkbox.net/packages/"))
      (package-initialize)
  • Install the package
    • Open emacs
      • M-x package-install RET geiser RET (RET is press <enter>)
You should now be able to run Racket mode by opening emacs and doing the following:

M-x run-geiser
> Start Geiser for scheme implementation: racket

This should start the REPL.


Sunday, 16 March 2014

Emacs: Racket on Ubuntu

Well, I'm finally digging into Emacs as a text editor for Lisp and Erlang.  I've picked up Learning GNU Emacs which I'm enjoying.  During my study with SICP, I'm using the Racket flavor of Scheme. 

One of the issues so far, though, has been how to be install and use Emacs with Racket on Ubuntu.  So, I don't forget I'm going to record what configuration I ended up using.

Emacs (extra-super text editor):
sudo apt-get install emacs

Geiser (Racket Scheme support for Emacs):
sudo apt-get install geiser

Quack (enhanced Scheme mode for Emacs):
sudo apt-get install emacs-goodies-el


After installing the tools above.  I open terminal session and type emacs -nw to open Emacs.

Once Emacs is open, in order to enter Racket mode, I use Geiser by running the following commands:

M-x run-geiser RET racket RET*

*RET - hit enter

At this point, you can open up a Racket REPL, by running:

C-c C-z

This will open up another buffer and start a Racket REPL in the window.

I tend to like to be editing a Racket file and then, when I'm ready load the file into the REPL for testing.  To do this, save a file:

C-x C-s  (then give a file name, ex. test.cl)

Add some Scheme definitions to the file and then save using the same command.  Then, when I'm ready to test run the following:

C-c C-a

This Geiser command will open a REPL and then load the current file into the REPL session.  This allows you to switch back and forth between the REPL buffer and the file buffer.  So far, I'm finding this to be the best configuration.


Sunday, 26 January 2014

SICP Insight

Recently, I've joined the Structre and Interpretation of Computer Programs (SICP) London meetup.  The meetup is run as a coding dojo switching pairs for each problem from the SICP book.  To support study of this book, there are some great lectures on the MIT Open Courseware website.

Keeping in mind these lectures were arranged for Hewlett-Packard in 1986, this section stood out.  By the way, these comments by Hal Abelson are during a discussion about creating a data abstraction for rational numbers (and don't worry about who George is).  The full transcript is available with the MIT course.
But the real issue is that you might not be able to decide at the moment you're worrying about these rational numbers. See, in general, as systems designers, you're forced with the necessity to make decisions about how you're going to do things, and in general, the way you'd like to retain flexibility is to never make up your mind about anything until you're forced to do it. 
The problem is, there's a very, very narrow line between deferring decisions and outright procrastination. So you'd like to make progress, but also at the same time, never be bound by the consequences of your decisions. Data abstraction's one way of doing this. What we did is we used wishful thinking. See, we gave a name to the decision. We said, make-RAT, numerator, and denominator will stand for however it's going to be done, and however it's going to be done is George's problem. 
But really, what that was doing is giving a name to the decision of how we're going to do it, and then continuing as if we made the decision. And then eventually, when we really wanted it to work, coming back and facing what we really had to do. And in fact, we'll see a couple times from now that you may never have to choose any particular representation, ever, ever. Anyway, that's a very powerful design technique. It's the key to the reason people use data abstraction. And we're going to see that idea again and again. Let's stop for questions. 
AUDIENCE: What does this decision making through abstraction layers do to the axiom of do all your design before any of your code? 
PROFESSOR: Well, that's someone's axiom, and I bet that's the axiom of someone who hasn't implemented very large computer systems very much. I said that computer science is a lot like magic, and it's sort of good that it's like magic. There's a bad part of computer science that's a lot like religion. And in general, I think people who really believe that you design everything before you implement it basically are people who haven't designed very many things. 
The real power is that you can pretend that you've made the decision and then later on figure out which one is right, which decision you ought to have made. And when you can do that, you have the best of both worlds.

This is such a clear explanation for so many parts of good software design.  In a couple of minutes, Prof. Abelson goes to the heart of modular design, abstraction layers, deferring design decisions, and iterative development practice.  Just goes to show that the proper way to do this hasn't changed in a while (even though it sometimes is packaged differently).

Wednesday, 27 March 2013

Actions and Funcs (part 4).....Onions

It has been a while since my last post.  Hopefully, it will be useful to continue this series a bit.  In the past few posts about Actions and Funcs in C#, I have covered a few techniques where delegating responsibility for behavior to the client can be useful.

In this post, I want to cover another usage for Actions and Funcs in the context of Domain Driven Design (DDD) or Onion Architecture.  In fact, for this article, it would be better to think in terms of the Onion instead of DDD.

Simply, the Onion Architecture protects the core business logic (domain) from all of the application concerns.  However, pretty soon when crafting a wicked domain, the domain needs to perform some kind of behavior based on the result of a business rule.  Maybe a concrete example will help here.

Let's say we have a domain entity named  Order and the Order entity is involved in a workflow that is modeled using State Pattern.  For this example, we won't concern ourselves with all of the Order workflow.  All I want to focus on is when the Order is ready to be placed by using the Place method:


So, the question is, how do we send an email confirmation to the Customer without mixing our application level concerns (like SMTP services etc) with our domain entities?  Well, lets explore our options.
  1. Create an interface called ISendEmail and make Order depend on it
  2. Pass in the ISendEmail inteface to the Place method
  3. Use an Action to fulfill the Sending of the Email
I'm going to work through these one at a time and comment on each.
First, why not just have Order depend on ISendEmail.  


This is the first step towards creating a domain model that is not sustainable.  Already we are bleeding application services into our domain entities.  Should the Order entity be able to exist without a way of sending an email?  If the answer is yes, then ISendEmail has no business being in the constructor.  Also, what if we decide not to send emails at some point in the future.  Do we really want to make a "do nothing" implementation for this case?

The second option is a bit more viable.  We pass in the dependent interfaces to the Place method:



At least this option localizes our use of the ISendEmail interface.  However, it still feels like the code sendEmail.ConfirmationTo(customer.EmailAddress) doesn't really below in the Order entity.  In most real scenarios, the ConfirmationTo method will need to know a lot more about the Customer and Order in order to build an email message dynamically.  Keeping all of that out of the Order entity is important when attempting to separate its concerns (the order workflow) with fulfillment concerns (sending the confirmation email).  So, now let's look at using an Action:


You can see right off, that using an Action does not expose the inner workings of the actual email fulfillment.  ISendEmail is not exposed inside the entity.  To make this really clear, let's see one of our domain services that will use the Place method:

What the Action is allowing us to do here, is inject the notification, but not tie our entity directly to the application service that will be doing our fulfillment.  When designing clean domain models, I really like this approach.  It allows the domain's business rules to run in isolation of the behaviors that are dependent on them and creates a nice separation between the domain and application level concerns.
Hope this helps.

Sunday, 22 April 2012

Actions and Funcs (part 3).....Func as Selector

Hello again.
This post is the third in my exploration of the usage of Actions and Funcs in building more expressive syntax for libraries.  So far, the posts in this series are:

1. Actions and Funcs.....Intro
2. Actions and Funcs (part 2).....Actions as Builder

So, another cool simple usage of Funcs when designing an API are as a selector.  Funcs provide a nice way to select one of many options while still providing a smart default.  So lets jump into some code:


The small console program above shows a selection of an enum (Color) for a Brush.  You can see in the ChooseColor method we send in Color.Yellow as the default.  This allows us to select the input parameter itself as the Color with the first selection line brush.ChooseColor(c => c);. In the second selection line brush.ChooseColor(c => Color.Red);, the Color.Red is selected. As expected, this program outputs:

Choose Default: Yellow Color Selected: Red Press <enter> to close.

When seeing code like this for the first time, I was confused. I thought, "What exactly is returning a value?". Then I found out a cool piece of syntactic sugar built into Func<T, T>. Basically, if the implementation of the Func<T, T> is a single line (so what is on the right-hand side of the => operator), the compiler will place a return before the code for you. So after compiling brush.ChooseColor(c => Color.Red); becomes brush.ChooseColor(c => { return Color.Red });. This allows for much cleaner and expressive code for examples like this. By the way, if you want a multi-line Func<T, T> then it will require the curly braces.

Well, that is about all I have this time. I think this is a cool little example of where Func<T, T> can make code expressive in a different way and might provide another option when designing a class that selects a value type like Color. Hope this helps.

Tuesday, 10 April 2012

Actions and Funcs (part 2).....Action as Builder

Following on from my last post about Actions, Predicates, and Funcs; I want to provide an example of one place that I've seen a framework successfully use an Action as in an API.  Recently, I've been doing some work with NServiceBus (NSB).  NSB gives a nice terse way to Send or Publish a new message.  It looks like this:


This code uses an Action<T> underneath to create a new instance of the type that is going to be sent or published.  What is extra cool about this is that NSB allows you to define values for properties of an instance that it will dynamically generate.  Like the example above, this allows NSB to give the impression that it can assign values directory to interface properties!

So, how can we allow users of our API to define properties, but keep hold of the specifics about how we create an object?

Action<T> as Builder
Like NSB, we can take in an Action<T> and allow the user of the API to build the object they desire.  To show the specifics of how to do this, I'll complete a non-production version of what NSB does.  So, first we need to define the IBus interface:


And this is a simple implementation for IBus:



A bit of explanation
So, it turns out that the code is quite simple for a pretty cool API feature.  The implementation of IBus only needs to understand the type of the message, then can create a blank instance, and pass the instance to the action for building.  At this point, the action implementation (defined in the method call to IBus.Publish<T>) takes over and fills in all the properties.  This works because T has to be an IMessage (which means it must be a reference type). Nice.  Using this type of technique would also allow the framework code to make a default instance (with some properties set) and let these values to be changed during the action implementation.

More to come...

Thursday, 29 March 2012

Actions and Funcs

For a long time now, I have been wanting to better understand Action<T>, Func<T1, T2>, and Predicate<T> in C#.  I have always understood that they are generic delegates, but I never could get where they are most appropriate to be used when designing a library or framework for other developers to use.  I did see examples in libraries like linq, AutoMapper, and RhinoMocks where I thought the usage of Actions or Funcs as extension points made a lot of sense.

So, with this in mind, I'm planning to devote a couple of posts about an exploration into Action<T>, Func<T1, T2>, and Predicate<T>.  Hopefully, by recording this journey I'll take more from it and even perhaps help a few other developers to better embrace these tools.

What?
In this post, I just want to do a quick introduction to what Action<T>, Func<T1, T2>, and Predicate<T> are.  As I mentioned, these classes seem to be just another way to express a delegate in C#.  So why are they needed?  There seem to be many answers to that question.  First off, they allow for lambda expressions in C#, they are much more terse than anonymous delegates, and in my opinion they express a function pointer in a more direct way than a traditional delegate.  Plus, they are fun and make code more expressive.

Action<T>, Func<T1, T2>, Predicate<T> and delegates for that matter are just function pointers.  They allow functions to be passed around in code as data.

Events
The place where most people have seen this the most is with C# events.  An event needs a delegate type in order to know what type of function it can register.  Then when you register that OnLoad event for example, the compiler will only allow a callback method to register against the event that conforms to the correct signature.




In the above example, we are defining a delegate with the common .NET event signature void (object sender, EventArgs e). This comes in handy when we want to wire up a callback function that will listen out for when the event fires.  Underneath, the complier is going to make a new collection of OnLoadHandler delegate types and add (+=) or remove (-=) callbacks from the collection.  Then when the event is fired, the collection will iterate and call all the registered functions.


So, events is one place that many developers are familiar with delegates.  Since Action<T> is a void returning generic delegate, can we use it instead.  Yes, and here is the code:



As you can see, we have eliminated the need for a delegate to be defined in the Page class.  And what is better, we got rid of that Page.OnLoadHandler scoping issue when we registered the event.  The Action<T> can be registered against the event and all the functions stay roughly the same.  This is pretty cool, however, with EventHandler<T> out there not that useful.  This is more of an example to get warmed up for more to come.

Alright, got it
It's easy to see what is going on here.  Action<T> allows us a better way to express a delegate.  So now it's time to define these guys.

Action<T>
Actions are delegates that always return void.  Each generic type defined (and in the same order) become the type of the parameter in the function.

Func<T1, T2>
Funcs are the most expressive generic delegate form.  They take at least two generic type arguments because the last one is always the return type of the delegate signature.  So, in this case T2 is the type that you want to return.

Predicate<T>
Predicates are Funcs that always return a boolean value.  All of Predicate's generic type arguments define the parameters in its delegate signature.

In the next post, I'll dig a bit deeper into some more typical usages for API design.  See ya then!