Phil Trelford's Array
POKE 36879, 255

Date Types

April 26, 2014 09:21 by phil

When you want to set a date literal in F# (or C#) you create a new DateTime instance:

let today = DateTime(2014,26,4)

If you’re rocking VB.Net you get date literals which are checked at design & compile time:

Dim d = #2014/04/26#

I thought it’d be nice to add design and compile time checked date literals to F#, & throw in code completion for good measure. Enter F# Type Providers. No need to open millions of lines of compiler code, instead simply implement a class to provide the types & voilà:

let today = Date.``2014``.``04``.``26``

As you type the date, you can only enter valid values:

today

Or you can for example use it to easily find the last Saturday of the month:

saturday

The code is up on BitBucket & there’s a Nuget package, it’s pretty simple, less than a 100 lines of code, and no compilers were harmed in the process. Being what it is, this is really just scratching the surface of the power of F# Type Providers, which can give you typed access to data from web services or databases all the way through to other languages.

Build your own Type Provider

Creating your own type providers is easier than you might think, Michael Newton has a great article to get you started: Type Providers From the Ground Up.

F#unctional LondonersCoincidentally the F#unctional Londoners will be hosting a Creating Type Providers Hands On Session with Michael next Thursday at Skills Matter.

Pop along, have fun, and see the kind of things you can build.


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

Case for VB.Net vNext

April 5, 2014 03:50 by phil

Following up on the last Roslyn preview way back in 2012, this week saw the availability of a new preview with a more complete compiler along with a few new language features for C# and VB. A lot of inspiration for these features seems to have come from the F# language.

The C# interactive shell from 2012 appears to be missing, perhaps ScriptCS is expected to fill this space, or you could just use F# interactive which already exists in Visual Studio.

On the language features side, C# 6 gets primary constructors for classes, heavily inspired by F#, and using static which brings parity with Java and VB.Net.

For me VB.Net gets the most interesting new feature in the form of Select Case TypeOf. which provides the first steps towards pattern matching.

Shapes

Taking a hierarchy of shapes as an example:

Public MustInherit Class Shape
End Class

Public Class Rectangle
    Inherits Shape
    Public Property Width As Integer
    Public Property Height As Integer
End Class

Public Class Circle
    Inherits Shape
    Public Property Radius As Integer
End Class

Sub Main()
    Dim shape As Shape = New Rectangle With {.Width = 10, .Height = 10}
    Select Case shape
        Case r As Rectangle When r.Width = r.Height
            Console.WriteLine("Square of {0}", r.Width)
        Case r As Rectangle
            Console.WriteLine("Rectangle of {0},{1}", r.Width, r.Height)
        Case c As Circle
            Console.WriteLine("Circle of {0}", c.Radius)
    End Select
End Sub

The functionality is still quite limited and quite verbose in comparison to say F# or Scala, but I feel it’s definitely an interesting development for VB.Net.

For comparison here’s an equivalent F# version using discriminated unions:

type Shape =
    | Rectangle of width:int * height:int
    | Circle of radius:int

let shape = Rectangle(10,10)
match shape with
| Rectangle(w,h) when w=h -> printfn "Square %d" w
| Rectangle(w,h) -> printfn "Rectangle %d, %d" w h
| Circle(r) -> printfn "Circle %d" r

Eval

Pattern matching can be really useful when writing compilers, here’s a simple expression tree evaluator in F#:

type Expression =
   | Factor of value:int
   | Add of lhs:Expression * rhs:Expression

let rec eval e =
   match e with
   | Factor(x) -> x
   | Add(l,r) -> eval l + eval r

let onePlusOne = Add(Factor(1),Factor(1))

VB.Net vNext can approximate this, albeit in a rather more verbose way:

Public MustInherit Class Expression
End Class

Public Class Factor
    Inherits Expression
    Public Property Value As Integer
    Sub New(x As Integer)
        Value = x
    End Sub
End Class

Public Class Op
    Inherits Expression
    Public Property Lhs As Expression
    Public Property Rhs As Expression
End Class

Public Class Add
    Inherits Op
End Class

Function Eval(e As Expression) As Integer
    Select Case e
        Case x As Factor
            Return x.Value
        Case op As Add
            Return Eval(op.Lhs) + Eval(op.Rhs)
        Case Else
            Throw New InvalidOperationException
    End Select
End Function

Sub Main()
    Dim onePlusOne As Expression =
        New Add With {.Lhs = New Factor(1), .Rhs = New Factor(1)}
    Console.WriteLine(Eval(onePlusOne))
End Sub

Summary

It will be interesting to see how VB.Net vNext develops. I think first-class support for tuples could be an interesting next step for the language.


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

Orleans

April 3, 2014 10:28 by phil

Microsoft’s Build 2014 conference is currently in full flow, one of the new products announced is Orleans, an Actor framework with a focus on Azure.

There’s an MSDN blog article with some details, apparently it was used on Halo 4.

Demis Bellot of ServiceStack fame, tweeted his reaction:

I retweeted, as it wasn’t far off my initial impression and the next thing I know my phone is going crazy with replies and opinions from the .Net community and Microsoft employees. From what I can make out the .Net peeps weren’t overly impressed, and the Microsoft peeps weren’t overly impressed that they weren’t overly impressed.

So what’s the deal.

Actors

Erlang has distributed actors via OTP, this is the technology behind WhatsApp, recently acquired for $19BN!

The JVM has the ever popular Akka which is based heavily on Erlang and OTP.

An industrial strength distributed actor model for .Net should be a good thing. In fact Microsoft are currently also working on another actor framework called ActorFX,

The .Net open source community have projects in the pipeline too including:

There’s also in-memory .Net actor implementations with F#’s MailboxProcessor and TPL Dataflow. Not to mention the departed Axum and Retlang projects.

Orleans

From what I can tell, Orleans appears to be focused on Azure, making use of it’s proprietary APIs, so there's probably still a big space for the community's open source projects to fill.

Like Demis I’m not a huge fan of WCF XML configuration and code generation. From the Orleans MSDN post, XML and code-gen seem to be front and centre.

You write an interface, derive from an interface, add attributes and then implement methods, which must return Task<T>. Then you do some XML configuration and Orleans does some code generation magic for hydration/dehydration of your objects (called grains).

Smells like teen spirit WCF, that is methods are king, although clearly I could be reading it wrong.

From my limited experience with actors in F# and Erlang, messages and message passing are king, with pattern matching baked into the languages to make things seamless.

Initial impressions are that Orleans is a long way from Erlang Kansas…

The Good Parts

Building a fault-tolerant enterprise distributed actor model for .Net is significant, and could keep people on the platform where they may have turned with Erik Meijer to the JVM, Scala and Akka otherwise.

Putting async front and centre is also significant as it simplifies the programming model.

C# 5’s async is based on F#’s asynchronous workflows, which was originally developed to support actors via the MailBoxProcessor.

Coroutines

Underneath, Erlang’s processes, F#’s async workflows and C#’s async/await are simply implementations of coroutines.

Coroutines are subroutines that allow multiple entry points for suspending and resuming execution at certain locations. They’ve been used in video games for as long as I can remember (which only goes back as far as the 80s).

Coroutines help make light work of implementing state machines and workflows.

Methods

In Erlang messages are typically described as named tuples (an atom is used as the name), and in F# discriminated unions are typically employed.

Orleans appears to use methods as the message type, where the method name is analogous to an Erlang atom name, or an F# union case name and the parameters are analogous to a tuple. So far so good.

Where they differ is that return values are first-class for methods, and return values feel more like an RPC approach. In fact this is the example given in the article:

public class HelloGrain : Orleans.GrainBase, IHello
{
  Task<string> IHello.SayHelloAsync(string greeting)
  {
    return Task.FromResult("You said: '" + greeting + "', I say: Hello!");
  }
}

Also current wisdom for C# async is to avoid async void... which is why I guess they’ve plumped for Task as the convention for methods with no return value.

Messages

.Net’s built-in binary serialization is bottom of the league for size and performance, hopefully alternative serialization libraries like Google Protocol Buffers will be supported.

Judge for yourself

But these are just my initial impressions, try out the samples and judge for yourself.


Tags:
Categories: .Net | C# | F# | Erlang | Scala | Architecture
Actions: E-mail | Permalink | Comments (2) | Comment RSSRSS comment feed