WebSharper
By Adam Granicz on Wednesday, February 10, 2010 — 0 comments

WebSharper 2010 Standard coming soonCore team

Hi everyone, and thanks for the emails asking about the delay in launching WebSharper 2010 Standard. A few days ago an internal release of Visual Studio 2010 RC was made available by Microsoft to various industry partners including ourselves for testing before the public release. As it came right at our official launch date we had to make the hard decision to “silently” postpone releasing WebSharper 2010 Standard until we finished thoroughly testing it on the new Visual Studio.

Now that VS 2010 RC is publicly available, we can finally let you know about the delay. There is a long list of enhancements that have gone into the 2010 Standard product line that were not available in our previous trial drops, and we are excited about this new release bringing a truly unbeatable value.

By Anton Tayanovskyy on Monday, January 25, 2010 — 0 comments

WebSharper 0.4.74Core team

A new release of WebSharper (0.4.74) is made available for download today. It contains bugfixes, an improved RPC system that has been revised for optimal performance, and various improvements to the Formlets API. Formlet rendering configuration is now parameterized, allowing, for example, to alternate the row colors in formlet tables. Several new formlets (radio button groups and multi-select check boxes) have been added to the collection.

We are currently working towards a major release scheduled on February 9. The new release will finalize the APIs and bring major improvements to WebSharper builds and error reporting.

By Anton Tayanovskyy on Thursday, January 7, 2010 — 0 comments

Default Constructors and the Singleton PatternCore team

In this blog I will demonstrate a common F# idiom for passing values through the type system.

The need for this usually comes as you are trying to trick F# into doing something advanced. Typically, you write a function F accepting a type paremeter 'T and expecting to use some functionality that 'T provides. Passing instances of 'T is not always a good option, as passing types is much cheaper syntactically (thanks to the type inferencer).

This can be done by constraining 'T to implement an interface I. However, unlike Java, .NET interfaces cannot constrain static members. Thankfully, this can be resolved by default constructor constraints and on the type coupled with type initialization.

1
2
3
4
5
6
    type IFoo =
        abstract member Bar: unit -> unit

    let F<'T when 'T :> IFoo and 'T : (new : unit -> 'T)>() =
        let t = new 'T()
        t.Bar()

The remaining problem is the generated GC load, as new instances of 'T are created at every invocation of F.
A way to go here is to use the Singleton pattern:

1
2
3
4
5
6
7
8
9
10
    [<Sealed>]
    type Singleton<'T when 'T : (new : unit -> 'T)> private () =
        static let instance : 'T = new 'T()
        static member Instance : 'T = instance

    type IFoo =
        abstract member Bar: unit -> unit

    let F<'T when 'T :> IFoo and 'T : (new : unit -> 'T)>() =
        Singleton<'T>.Instance.Bar()

The GC time advantages of using the singleton can be easily measured:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
module A = 
    let F<'T when 'T :> IFoo and 'T : (new : unit -> 'T)>() =
        (new 'T() :> IFoo).Bar()

    let G<'T when 'T :> IFoo and 'T : (new : unit -> 'T)>() =
        (Singleton<'T>.Instance :> IFoo).Bar()

#time    

for f in 0 .. 10000000 do
    A.F<Foo>()

// Real: 00:00:01.465, CPU: 00:00:01.453, GC gen0: 114, gen1: 0, gen2: 0

for f in 0 .. 10000000 do
    A.G<Foo>()

// Real: 00:00:00.544, CPU: 00:00:00.546, GC gen0: 0, gen1: 0, gen2: 0
By Adam Granicz on Wednesday, December 23, 2009 — 0 comments

WebSharper 0.4.62 is available - with dependent formlets-flowlets-third-party extensions-and more!Core team

We are happy to announce the availability of WebSharper 0.4.62 - the latest version of the WebSharper Platform that aims to equip professional F# developers with the right platform to rapidly develop rich, scalable, client-based web applications. This is the first release candidate of WebSharper Platform 2010 - our commercial offering for client-based reactive web development with F#. In this release there are a number of new features, including:

  • Dependent formlets - an embedded DSL for describing formlets whose parts depend on other parts of the same or other formlets.
  • Flowlets - an embedded DSL for describing sequences of web forms (such as steps in a registration page) as a strongly typed, first-class value in F#.
  • Extensions for the Google Maps API - you can build rich, interactive maps, street views, route planners, and other navigational functionality using the Google Maps API through WebSharper bindings - all with F# code and without a single line of JavaScript.
  • Extensions for the Google Visualization API - you can create stunning interactive visualizations (maps, charts, graphs, gauges, etc.) using the Google Visualization API through WebSharper - again, all with F# code.
  • First-class resources - pagelets can define their dependencies and the resources they need inside the F# type system, making it type-safe and robust, and freeing you from having to track various artifacts (style sheets, images, includes, etc.).

Go and grab your copy at our download page, or check out the demos we have online (and don't forget to use the drop-down on the right to see all demos). More demos, tutorials, and some long-awaited screencasts will be coming shortly.
One last bit: you may get exceptions in Visual Studio debug mode (which is misleading, as most of your WebSharper code will be executing in the client browser) from WebSharper code that performs HTML construction - you can safely ignore these as the WebSharper ASP.NET integration layer will take care of them. We are working on removing this annoyance in the next release candidate.

By Anton Tayanovskyy on Friday, December 11, 2009 — 0 comments

Foldr or FoldBack on Infinite F# SequencesCore team

A noticeable omission in F# standard library is Seq.foldBack, or the famous Haskell foldr. The semantics of foldr is very simple to remember: it replaces the native cons and nil of a list with arbitrary computations:

1
2
    foldr cons nil []     = nil
    foldr cons nil (x:xs) = cons x (foldr cons nil xs)

In particular, replacing the native cons and nil with themselves is always equivalent to the original list, e.g. forall x: foldr (:) [] x == x

Surprisingly, the above equation holds for infinite lists as well. This is something important to remember when porting these ideas to F#.

A naive F# translation would use this type:

1
 foldBack : ('T1 -> 'T2 -> 'T2) -> 'T1 -> seq<'T1> -> 'T2

However, by being strict in the second argument, cons will now prematurely force the evaluation of infinite sequences.

Here is a more faithful translation using LazyList from the FSharp.PowerPack.dll:

1
2
3
4
5
6
    /// Implements the lazy right-to-left fold.
    let foldBack (f: 'T1 -> Lazy<'T2> -> 'T2) (z: 'T2) (xs: seq<'T1>) : 'T2 =
        let rec foldr = function
            | LazyList.Nil         -> z
            | LazyList.Cons(x, xs) -> f x (lazy (foldr xs))
        foldr (LazyList.ofSeq xs)

Now let us test the code to make sure we have been faithful to Haskell in our translation:

1
2
3
4
5
6
7
8
    Seq.FoldBack 
        (fun x xs -> LazyList.consDelayed x (fun () -> Lazy.force xs)) 
        (LazyList.empty ())
        (Seq.initInfinite (fun x -> x))
    |> LazyList.toSeq
    |> Seq.take 10
    |> Seq.toArray
    |> printfn "%A"
By Anton Tayanovskyy on Thursday, December 10, 2009 — 0 comments

Generic Workflow Builders (Monads) in F#Core team

This blog post is about a quick and dirty encoding of Haskell type classes in F#. With the ongoing work on the WebSharper™ project, we are currently very interested in coaxing the .NET type system to support writing code that is generalized over monads and applicative functors. I thank Sandro Magi and refer to his excellent blog posts with C# code that explain the general technique. Here I will just give sample code.

The problem to solve is to define a generic workflow (monad) builder, in such a way that the user can write code parameterized over the monad. The solution sacrifices type safety by using downcasts. However, with very mild assumptions, the downcasts are always safe. The technique scales to other Haskell type classes such as Applicative.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
type IMonad<'M when 'M :> IMonad<'M> and 'M : (new : unit -> 'M)> =
    abstract member Return<'T> : 'T -> IMonad<'T,'M>
    abstract member Bind<'T1,'T2> : IMonad<'T1,'M> * ('T1 -> IMonad<'T2,'M>) -> IMonad<'T2,'M>    
    
and IMonad<'T,'M when 'M :> IMonad<'M>> = interface end

[<Sealed>]
type MonadBuilder<'M when 'M :> IMonad<'M> 
                     and 'M : (new : unit -> 'M)> private () =
    
    let m = new 'M() :> IMonad<'M>
    static let self = new MonadBuilder<'M>()
    
    static member Instance : MonadBuilder<'M> = self

    member this.Return<'T>(x: 'T) : IMonad<'T,'M> = 
        m.Return x

    member this.Bind(x: IMonad<'T1,'M>, f: 'T1 -> IMonad<'T2,'M>) : IMonad<'T2,'M> =
        m.Bind(x, f)

    member this.Delay<'T,'R when 'R :> IMonad<'T,'M>>(f: unit -> IMonad<'T,'M>) : 'R = 
        m.Bind (m.Return (), f) :?> 'R

type Maybe<'T> =
    | Nothing
    | Just of 'T

    interface IMonad<'T,MaybeInstances>

and MaybeInstances () =
    interface IMonad<MaybeInstances> with
        member this.Return x =
            Just x :> _

        member this.Bind(x, f) =
            match x :?> _ with
            | Nothing -> Nothing :> _
            | Just x  -> f x

let maybe = MonadBuilder<MaybeInstances>.Instance

maybe {
    let! x = Just 1
    let! y = Just 5
    return x + y
}
|> printfn "%A"

There are several things to notice. First, monad builders can be constructed with MonadBuilder .Instance by passing a complying T. Second, monad-generalized functions such as Control.Monad.Sequence from Haskell prelude are expressible with the IMonad interface pair.

One serious drawback is the inability to define instances on existing types, such as seq. This can be worked around by using isomorphic new types, but those require explicit (un)wrapping.

Nevertheless, the technique seems applicable enough. If things go well, the code can make it into a library.

By Anton Tayanovskyy on Wednesday, December 9, 2009 — 0 comments

WGET in F#Core team

Once every while I have to remind myself that I can program, and that the task at hand can be automated. On the most recent occasion, I was trying to write down the dependency graph for Yahoo User Interface (YUI) modules, when it finally occurred to me that the dependencies are documented in source code, and the source code is available online. The task was doable within 30 lines of F#. I would like to share the fun part, implementing an asynchronous WGET, designed as a function from a URL to a string of its contents. With using the built-in Async.Parallel predicate on 30 or so requests constructed, I was able to observe a significant improvement in the program's responsiveness. It is nice to have .NET network libraries available at your fingertips. Even when their APIs are not exactly convenient, you can typically wrap them in a nice manner.

1
2
3
4
5
6
7
8
9
    let Fetch (url: string) =
        let read (response: System.Net.WebResponse) =
            use reader = new System.IO.StreamReader(response.GetResponseStream())
            reader.ReadToEnd()
        async {
            let request = System.Net.WebRequest.Create url
            let! response = Async.FromBeginEnd(request.BeginGetResponse, request.EndGetResponse)
            return read response
        }
By Anton Tayanovskyy on Tuesday, December 8, 2009 — 0 comments

The Execution Speed of Early vs Late Binding in .NETCore team

This little post documents one of my little experiments with F#, as I am educating myself on the .NET Framework fundamentals.

The interesting issue is the execution speed of late vs early-bound code. Open the F# interactive and try this out.

1
2
3
4
/// A dummy type.
type T = 
    /// This is the method we want to call.
    static member F x = x + 1

Turn on timing in the Interactive:

1
#time

First, let as assume we know the type and the method signature at compile time. This is early, static binding, and the result is fast:

1
2
3
for i = 0 to 1000000 do
    T.F 1 
    |> ignore

Now suppose we do not know type T at compile time, but rather have a System.Type object to represent it.

We could then use reflection to invoke the method, as below, but it is slow, several orders of magnitude slower in fact.

1
2
3
4
let m = typeof<T>.GetMethod("F")
for i = 0 to 1000000 do
    m.Invoke(null, [| box 1 |])
    |> ignore

If we do not know the type T, but do know the method signature, we can do a lot better using delegates. This is fast:

1
2
3
4
5
type F = delegate of int -> int
let  f = System.Delegate.CreateDelegate(typeof<F>, typeof<T>, "F") :?> F
for i = 0 to 1000000 do
    f.Invoke 1 
    |> ignore
By Anton Tayanovskyy on Tuesday, December 8, 2009 — 0 comments

WebSharper - Write F# and Run JavaScriptCore team

It is an exciting time to be working for IntelliFactory. After quite a bit of hard work, we finally have a public beta release of the WebSharper™ platform. As we continue to work on it, I encourage you to download and play with the current beta release.

WebSharper™ aims to change the way you think about web programming, no more and no less. The idea behind it is very simple. Instead of HTML + JavaScript + PHP/C#/Java code, you write F#, and let the compiler do its magic to get a working AJAX website. Alternatively, you develop a small component and expose it as an ASP.NET control, without having to rewrite your website from scratch.

Let me start with a simple, indeed primitive, example. Let us take the the first problem from Project Euler (a great source of profitable amusement for many of us), solve it in F#, and run it in the browser. To play with it, download and install the beta release of the WebSharper™ platform, start a new WebSharper solution, and change the project code to the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    namespace WebSharperProject

    open IntelliFactory.WebSharper
    open IntelliFactory.WebSharper.Html 

    [<assembly: WebSharperAssembly>]
    do ()

    [<JavaScriptType>]
    module Math = 

        /// Find the sum of all the multiples of 3 or 5 below 1000.
        [<JavaScript>]
        let ProjectEuler0001 =
            seq { 0 .. 999 }
            |> Seq.filter (fun x -> x % 3 = 0 || x % 5 = 0)
            |> Seq.sum

    [<JavaScriptType>]
    type Example() = 
        inherit Web.Control()

        [<JavaScript>]
        override this.Body = 
            let answer = Span []
            Div [
                Div [
                    Span ["The answer is: "]
                    answer
                ]
                Input [Type "Button"; Value "Calculate"]
                |> On Events.Click (fun _ ->
                    answer.Text <- string Math.ProjectEuler0001)
            ]

Then change the Default.aspx to reference the newly defined Example control:

1
2
3
4
5
6
7
8
9
    <%@ Page Language="C#" %>
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
        <WebSharper:ScriptManager runat="server" />
      </head>
      <body>
        <ws:Example runat="server" />
      </body>
    </html>

This is a small example, but there is a lot to get excited about already. Take powerful F# type-checking, functional abstractions, embedded HTML combinators, or ASP.NET integration...

Yes, Project Euler problems are not exactly representative of the tasks a typical web programmer faces. But I firmly believe that a platform that makes difficult things possible should make simlpe things simple.

I will be blogging with more posts on WebSharper™ in the coming days. In the meanwhile, the impatient should definitely check out the Demos.

By Anton Tayanovskyy on Wednesday, December 2, 2009 — 0 comments

.NET Composite Formatting with Keyword ExpansionCore team

Composite Formatting is a feature of .NET framework that comes handy even for F# programmers. Yes, Printf-style formatting generally is much nicer with F#, but there are situations where the format string is not available statically. It can, for instance, be coming from a configuration file.

One common issue with Composite Formatting is that it is not immediately obvious how to expand named arguments. Fortunately, all the pieces of the puzzle are there.

Just a little bit of F#:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    module Format =
        open System
        open System.Collections.Generic

        let private Split (s: string) =
            match s.IndexOf '|' with
            | -1 -> (s, "")
            | n  -> (s.Substring(0, n), s.Substring(n + 1))

        type Table<'T>(dict: IDictionary<string, 'T>) =
            new (pairs: seq<string * 'T>) = 
                new Table<'T>(Map.ofSeq pairs)

            interface IFormattable with
                member this.ToString(format, _) =
                    let (key, def) = Split format
                    if dict.ContainsKey key then
                        dict.[key].ToString()
                    else
                        def

Now we can use string keys (and default values) to expand on keywords within the format strings. This is handy:

1
2
3
4
    let fmt = "{0:schema|http}://{0:domain}{0:path}"
    System.String.Format(fmt, Format.Table ["domain", "example.com"])
    System.String.Format(fmt, Format.Table ["domain", "example.com"; "path", "/products"])
    System.String.Format(fmt, Format.Table ["schema", "https"; "domain", "example.com"])

You can also pass Dictionary and Map objects to the Format.Table constructor.

Even better, Composite Formatting is available not only in String.Format but also in other places such as TextWriters.

As a functional programmer working with F#, I keep discovering basic .NET framework features. Even though this use of Composite Formatting must be trivial, I hope some of you will find it useful.