Phil Trelford's Array
POKE 36879, 255

TypeScript Mario

September 4, 2014 00:23 by phil

Earlier this year I had a play with Microsoft’s new compile to JavaScript language, TypeScript. Every man and his dog has a compile to JavaScript solution these days. TypeScript’s angle appears to be to provide optional static typing over JavaScript and some ES6 functionality while compiling out to ES3 by default. It provides a class based syntax similar to C#’s and seems to be aimed at developer’s attempting to scale out JavaScript based solutons.

Last year I ported Elm’s Mario sample to F#, which ended up looking similarly concise. I tried both FunScript and WebSharper for compiling F# to JavaScript, and both worked well:

mario

So I thought I’d try the sample out in TypeScript as a way to get a feel for the language.

TypeScript Interfaces

In F# I defined a type for Mario using a record:

// Definition 
type mario = { x:float; y:float; vx:float; vy:float; dir:string }
// Instantiation 
let mario = { x=0.; y=0.; vx=0.; vy=0.; dir="right" }

In TypeScript I used an interface which looks pretty similar syntactically:

// Definition
interface Character {
    x: number; y: number; vx: number; vy: number; dir: string
};
// Instantiation
var mario = { x:0, y:0, vx:0, vy:0, dir:"right" };

TypeScript transcompiles this to a JavaScript associative array using object notation:

var mario = { x: 0, y: 0, vx: 0, vy: 0, dir: "right" };

Composition

For me the cute part of the Elm and F# versions was using the record “with” syntax and function composition, i.e.

let jump (_,y) m = if y > 0 && m.y = 0. then  { m with vy = 5. } else m
let gravity m = if m.y > 0. then { m with vy = m.vy - 0.1 } else m
let physics m = { m with x = m.x + m.vx; y = max 0. (m.y + m.vy) }
let walk (x,_) m = 
    { m with vx = float x 
             dir = if x < 0 then "left" elif x > 0 then "right" else m.dir }

let step dir mario = mario |> physics |> walk dir |> gravity |> jump dir

I couldn’t fine either of those features available out-of-the-box in TypeScript so I resorted to imperative code with mutation and procedures:

function walk(velocity: CursorKeys.Velocity, character: Character) {
    character.vx = velocity.x;
    if (velocity.x < 0) character.dir = "left";
    else if (velocity.x > 0) character.dir = "right";
}

function jump(velocity:CursorKeys.Velocity, character:Character) {
    if (velocity.y > 0 && character.y == 0) character.vy = 5;    
}

function gravity(character: Character) {
    if (character.y > 0) character.vy -= 0.1;
}

function physics(character: Character) {
    character.x += character.vx;
    character.y = Math.max(0, character.y + character.vy);
}

function verb(character: Character): string {
    if (character.y > 0) return "jump";
    if (character.vx != 0) return "walk";
    return "stand";
}

function step(velocity: CursorKeys.Velocity, character:Character) {
    walk(velocity, mario);
    jump(velocity, mario);
    gravity(mario);
    physics(mario);
}

The only difference between the TypeScript and the resultant JavaScript is the type annotations.

HTML Canvas

TypeScript provides typed access to JavaScript libraries via type definition files. The majority appear to be held on a personal github repository.

Note: both FunScript and WebSharper can make use of these type definition files to provide types within F# too.

Among other things this lets you get typed access over things like the HTML canvas element albeit with some funky casts:

    var canvas = <HTMLCanvasElement> document.getElementById("canvas");
    canvas.width = w;
    canvas.height = h;

This has some value, but you do have to rely on the definition files being kept up-to-date.

Conclusions

On the functional reactive side TypeScript didn't appear to offer much value add in comparison to Elm or F#.

To be honest, for a very small app, I couldn’t find any advantages to using TypeScript over vanilla JavaScript. I guess I’d need to build something a lot bigger to find any.

Sample source code: https://bitbucket.org/ptrelford/mario.typescript


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

DDD North 2013

October 13, 2013 07:08 by phil

I’m heading home on the geek train back from a cracking DDD North, this year held in Sunderland and attracting 430 attendees and three well attended F# talks.

I managed to deliver the first pony of the day in F# eye for the C# Guy:


Starting with live samples of immutable classes in C# and then in F# using the class and record syntax. Then instantiating the classes via the F# interactive (REPL) window and from C# which simply requires a reference to the F# library project, it’s all .Net IL underneath.

Then we moved on to unit testing in F# using a selection of libraries from Nuget including NUnit, FsUnit and Unquote. On the unit testing theme Ian Cooper gave a talk on TDD, where did it all go wrong at the same time which was well received.

Leading on from unit testing we took a look at automated acceptance testing with TickSpec, and how this was used in the open source spreadsheet Cellz.

Finally for fun I showed a couple of FunScript samples including the Mario Tutorial (only working in IE at the moment) and a Pacman Sample. FunScript is an open source F# to JavaScript compiler with a Type Provider to TypeScript type definition files which provides typed access to common JavaScript libraries.

If you’re interested in picking up F# I’d recommend trying the F# Koans (where you can pick up the syntax while making a set of tests pass), the online Try F# site, and the F# Tutorial project in Visual Studio.

Hadoop Kickstarter

Next up in the same room Gary Short gave a great introduction to Hadoop and some of the related tools like Pig.

If you’re interested in trying out Hadoop with F# check out the Hadoop Type Provider online on the Try F# site which gives you typed access with intellisense:

Hadoop 

WTFP?! Functional Programming and why you should care, with examples in F#

Before lunch Grant Crofton gave a great introduction to functional programming with F# using lots of live code snippets in Visual Studio


 

Grant also managed to slip some ASCII art into his scripts :)

WTF ASCII Art

Lightning talks

Lunch time saw a selection of lightning talks including Ben Nunney on Twillio and Anthony Steele on Feature Folders which emphasised the importance of focusing on the problem domain in your architecture.

The Joy of Wires: an introduction to Netduino

After lunch I popped over to see Iain Angus’s lively talk on Netduino which showed how much fun it can be playing with electronics.

You've learnt the basics of F#: What's next?

The last session of the day for me was Ian Russell’s fun talk which covered a selection of F# Type Providers for typed data access and F# Agents for taming concurrency.

Audience at Ian's talk at DDD North

Ian demonstrated the SQL, CSV, JSON and World Bank type providers all available either bundled with F# or via Nuget. For F# agents he showed a simple chat server that he ran from F# interactive using a local web server.

You can get the samples from Ian’s github repository: DDDNorth F# Presentation

Testing Crap in Web Applications Like ASP.Net MVC

The last pony of the day was spotted in Rob Ashton’s talk/rant which unfortunately I missed as it was on at the same time as Ian’s:


Close

Hanging out at the close with my fellow F#ers, Ian and Grant:

FSharpers

 

A big thanks to the DDD North team especially Andy Westgarth for hosting a great event!


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

Mario

October 6, 2013 10:13 by phil

The Elm programming language has some fun game samples including Mario. Elm’s syntax is quite similar to F#’s so it turned out quite easy to port the Mario sample and use FunScript to compile the F# code to JavaScript:

Mario FunScript

Use the cursor keys to move Mario.

FunScript

With F# and FunScript you get to use Visual Studio (Windows) or Xamarin Studio (Mac), and get Intellisense over your code and JavaScript libraries via a Type Provider to TypeScript declaration files, which is nice.

The sample uses an F# record for state & function composition for Mario’s movement:

type mario = { x:float; y:float; vx:float; vy:float; dir:string }

let jump (_,y) m = if y > 0 && m.y = 0. then  { m with vy = 5. } else m
let gravity m = if m.y > 0. then { m with vy = m.vy - 0.1 } else m
let physics m = { m with x = m.x + m.vx; y = max 0. (m.y + m.vy) }
let walk (x,_) m = 
    { m with vx = float x 
             dir = if x < 0 then "left" elif x > 0 then "right" else m.dir }

let step dir mario = mario |> physics |> walk dir |> gravity |> jump dir

Alternatively the step function can be composed using the forward compose operator:

let step dir = physics >> walk dir >> gravity >> jump dir

FunScript is a lightweight open source F# to JavaScript compiler. It is still very much in development so if you want to take it out for a spin I’d recommend pulling the source directly from Zach’s Github repository (the current Nuget package is pretty old).

WebSharper

Another good option for F# to JavaScript compilation is WebSharper which is a mature, commercial offering from Intellifactory. I’ve ported the sample to WebSharper too:

The source code again is pretty close, with some minor differences in the way the JavaScript API’s are called. I’m pretty new to WebSharper, so found the slightly older WebSharper 2.4 the easiest version to get started with and adapted the HTML5 Canvas sample to get going.

WebSharper vs FunScript

Anton Tayanovskyy recently posted a WebSharper vs FunScript comparison.

To summarize:

  • FunScript aims to provide an easily extensible F# to JavaScript compiler for building client-side apps. The samples use a lightweight command line based web server built by Tomas Petricek so you don’t even need ASP.Net
  • WebSharper is a commercial enterprise scale web development platform with smooth integration with ASP.Net allowing seamless communication between client and server code

Which gives 2 good choices for creating web apps that target JavaScript with F# :)

For some more complete game implementations try:

  • Pacman (FunScript + HTML5 Canvas)
  • Pool (WebSharper + WebGL)

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