Phil Trelford's Array
POKE 36879, 255

Prototype

April 1, 2013 03:00 by phil

JavaScript is good, so as part of JavaScript the Good Parts, prototypal inheritance must be really, really good.

JS The Good Parts

Some time ago while I was working on a supply chain management system for a large UK based department store I came across some interesting C# code, here’s an example:

public class Customer : Address 
{ 
}

Clarence

Unfortunately Clarence above has no address, but thanks to Homeless Hotspots he is a Mac address. A stark warning of the implications of favouring inheritance over composition.

When asked the C# programmer said that they preferred inheritance as it was quicker to implement in C# than composition. For a single object it is easier to favour inheritance over composition in C#, even more so with C# 2.0 before the advent of auto-implemented properties. Here’s the somewhat more verbose Customer has an Address:

public class Customer
{
    private readonly Address _address = new Address();

    public Address Address 
    { 
        get 
        { 
            return _address; 
        } 
    }
}

The Gang of Four in their seminal Design Patterns book postulated in the first chapter that good object-orientated design should favour composition over inheritance. Unfortunately most people seem to skip the first chapter and dive head first into specific patterns like singleton, proxy and factory. Spring’s AbstractSingletonProxyFactoryBean shows the way:

i-dontalways-make-factory-beans-but-when-i-do-i-make-abstractsingletonproxyfactorybe

Arbitrary misuse of inheritance is not confined to enterprise developers, we only need to look at the Button class in WPF to see a long hierarchy and over 160 members.

Button Inheritance

Thankfully the Intellisense in Visual Studio 2012 has an intelligent search to help you find the needle in the haystack. In the future it may be possible to apply machine learning approaches for prediction so that we can scale from hundreds to thousands of members.

Prototypal Inheritance

Programmers often find JavaScript inheritance hard to understand. This is probably a good thing, creating a pit of success where composition is by default favoured over inheritance.

To this end I have implemented Prototypal Inheritance for C#. The source is available on BitBucket and I will publish a Nuget package for enterprise developers in the near future.

Prototype-based programming is actually quite a natural fit for C# particularly with the dynamic support introduced in C# 4, combined with the var keyword introduced in C# 3, it’s often hard to distinguish C# from JavaScript. 

Now for the science: in prototypal inheritance every object is a clone of another object.

clones


Pseudoclassical

Let’s start with the pseudoclassical JavaScript example from Douglas Crockford’s book:

var Mammal = function (name) { this.name = name; };
Mammal.prototype.get_name = function () { return this.name; };
Mammal.prototype.says = function () { return this.saying || ''; };
var myMammal = new Mammal('Herb the Mammal');
var name = myMammal.get_name(); // 'Herb the Mammal'

var Cat = function (name) {
    this.name = name;
    this.saying = 'meow';
};

Cat.prototype = new Mammal();

Cat.prototype.get_name = function () {
    return this.says() + ' ' + this.name + ' ' + this.says();
};

var myCat = new Cat('Henrietta');
var says = myCat.says(); // 'meow'
var name = myCat.get_name();

You can’t beat a good taxonomy of the animal kingdom to show the awesome power of OO. Now you can create almost exactly the same code in C# using the Prototype library:

var Mammal = Prototype.Constructor<string>((that, name_) => that.Name = name_);
Mammal.Prototype.GetName = (System.Func<dynamic, string>)(that => that.Name);
Mammal.Prototype.Says = (System.Action<dynamic>)(that =>
{
    string saying = that.Saying;
    Echo(saying);
});
var myMammal = Mammal.New("Herb the Mammal");
string herb = myMammal.GetName();
Echo(herb);

var Cat = Prototype.Constructor<string>((that, name_) =>
{
    that.Name = name_;
    that.Saying = "meow";
});

Cat.Prototype = Mammal.New();

var myCat = Cat.New("Henrietta");

string name = myCat.GetName();
Echo(name);
 
Henrietta

Prototypal

Again starting with a JavaScript prototypal example:

var myMammal = {
    name: 'Herb the Mammal',
    get_name: function () {
        return this.name;
    },
    says: function () {
        return this.saying || '';
    }
};

Now in C# taking advantage of anonymous objects:

var Class = Prototype.FromObject(new
{
    Name = "Hello",
    GetName = (System.Func<dynamic, string>)(that => that.Name)
});
dynamic myMammal = Class.New();

There it is, prototypal inheritance for C#, you’re welcome!


Tags:
Categories: C# | JavaScript
Actions: E-mail | Permalink | Comments (1) | Comment RSSRSS comment feed

Connect All The Things – MVP Summit 2013

February 20, 2013 10:08 by phil

On Tuesday I did a lightning talk at the MVP Summit in Bellevue on connecting to all things, from statistics to statistical programming languages with Intellisense and LINQ using F# Type Providers, a feature shipped with Visual Studio 2012:


 

Connecting to an Excel file:

Excel Provider

Querying users stored on SQL Azure:

query {
  for u in db.Users do
  where (u.UserId <> userId)
  select u
}

Querying genres via the Netflix API:

query {
    for g in ctx.Genres do
    where (g.Name = genre)
    for t in g.Titles do
    where (t.ReleaseYear ?<= 1959)
    where (t.ReleaseYear ?>= 1934)
    sortByNullable t.AverageRating
    skip nToSkip
    take nToTake
    select t
}

Running B-Movie Sample on Azure: b-movies.azurewebsites.net

Connecting to the World Bank:

type WorldBank = WorldBankDataProvider<"World Development Indicators">
let data = WorldBank.GetDataContext()

let countries () = 
 [| data.Countries.India        
    data.Countries.``United Kingdom``
    data.Countries.``United States`` |]

Rendering charts asynchronously using JavaScript High Charts using TypeScript definitions:

let render () = async {
 let opts = h.HighchartsOptions() 
 opts.chart <- h.HighchartsChartOptions(renderTo = "chart", ``type`` = "line")
 opts.title <- h.HighchartsTitleOptions(text = "School enrollment")

Running in the browser using FunScript (F# to JavaScript compiler):

Charting World Bank

Querying Hadoop Hive in the browser:

query {
 for i in hive.iris do
 groupBy i.``class`` into g
 select (g.Key, Seq.length g) 
}

 

Iris data


Tags:
Categories: F# | .Net | JavaScript
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Progressive F# Tutorials London 2012

November 4, 2012 16:03 by phil

First things first, a big thanks to the team at Skills Matter particularly Wendy and Anaïs for making this event happen.

progfsharp-670x180px

This year the tutorials were held over 2 days in the atmospheric Crypt in Clerkenwell:

Progressive F# PanelProgressive F# Panel Progressive F# PanelSimon Cousins & Tomas Petrick

Expect a return next year in London and New York.

Day 1

 

Practical Functional-first Programming with F#

dsyme

Friends don't let friends use null


An outstanding keynote from Don which built on the talk he gave at the Progressive .Net Tutorials earlier in the year, stacked full of nuggets. On measuring if you have a correctness problem in your code base Don suggests counting the occurrences of NullReferenceException in your bug database.

Don also demonstrated F# 3.0’s Type Provider feature, including a very interesting Hive type provider for Hadoop written by Matt Moloney.

 

Programming with the stars!

tomaspetricek

I generally avoid 'function' when showing the language to newcomers. Not a problem at #progfsharp :-)

nrolland

i'm going to the Progressive F# Tutorials at #SkillsMatter Nov 1-2 intense coding with the greats of #Fsharp! http://bit.ly/SMprogFsharp


To demonstrate how to tackle problems with F#, Tomas & Nicolas neatly solved the Reversi kata live on stage. They started by transforming a board to a 2D array and then searched the array for legal moves.

 

F# Koans

chrismarinos

Ready for some koans fun at #progfsharp!


The F# Koans are a simple, fun, and interactive way to learn the F# language through testing. You can run them from VS2010 or VS2012. My 10yo really enjoyed working his way through them.

 

Processing concurrent time-series data

simontcousins

See you at the Progressive F# Tutorials 2012 http://t.co/y1FG9GGe


tomaspetricek

Not to miss #fsharp events! Tutorials at #skillsmatter in 2 weeks & Type-providers and financial tutorial at #techmesh tomasp.net/blog/…


Simon worked through some of the techniques he has used while developing solution in F# at E.ON Energy Trading for the last 4 years. There was also some ASCII art

 

Expert Panel Discussion

nickpalladinosmartintrojerdanielegloffcolinbulrobertpijonharrop

A very lively and fun debate, covering topics from industrial use of F#, cross-platform with Mono and the JVM, to data parallelism. Jon offered that several teams at Aviva, one of the world’s largest insurers, are using F#. Martin felt that F# on the JVM would be a smash hit. Finally Nick wetted our appetite for the upcoming release of {m}brace.

 

Day 2

 

Accelerate your TDD cycle – Coding dojo with NaturalSpec and NCrunch

sforkman

yfrog.com/h4h4yzej turns out the whole "in the crypt" thing - not a joke. #progfsharp

In this session Steffen introduced TDD with F# using NaturalSpec and NCrunch.

 

Make Music in the Key of F#

robertpi

@AnaisatSM thanks for having us, it really was a lovely event! /cc@skillsmatter @wendydevolder @ptrelford

 

Robert introduced Undertone a library for creating notes in F#, part inspired by Clojure’s Overtone. With the F# Koans under his belt my 10yo was able to translate the Baa Baa Black Sheep sample to Jingle Bells :)

 

F# in the Cloud

gmstavroulakisgianntzik

In this session, George and Gian demonstrated that F# can be used to perform computations in a cloud environment, using distributed actors, Azure Hadoop and the cool F# newcomer, {m}brace.

 

Web Programming

oenotriaptrelford

James started by talking through the F# MVC project template from Daniel Mohl.

After a short tea break I demonstrated some F# 3 type providers starting with accessing Stack Overflow’s API using the F# team’s OData type provider, followed by the file system and Freebase providers which are available in FSharpx via Nuget. Finishing up with a demo of the F# team’s B-Movie Madness sample web application which I’ve deployed on Azure.

James followed on with a site built using tube passenger statistics from TfL and a CSV type provider. Finally James demonstrated WebSharper compiling F# code directly to JavaScript.

 

Community Action

Thanks for stopping by, hope to see y’all at some of the upcoming fun F# community events:


Tags:
Categories: F# | .Net | JavaScript | Clojure | Twitter
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed