Phillip Trelford's Array

POKE 36879,255

F# on Android

Android games are now out-selling games for Sony and Nintendo handhelds. Thanks to the nice people at Xamarin you can now develop Android and iOS apps using all your favourite .Net languages:

Xamarin.Android 4.8.0 - New Features - F# support

Now it has been possible to target F# on Android and iOS for some time. In the latest release FSharp.Core is included and a blessed dll for the 64kb limit on trial versions.

Windows

You can use Xamarin.Android inside Visual Studio 2012 on Windows, which is how I got started. But I’d recommend giving Xamarin Studio a go, it has all the features you’d expect like intellisense and debugging.

Mac

In my opinion Xamarin Studio on Mac really whips the llamas ass!

On OS X you get a full suite of project options for Android:

full suite of F# projects in Xamarin Studio on Mac

And ASP.Net if that’s your thing:

ASP.Net from Xamarin Studio on Mac

There’s plenty of project options but there’s little in the way of WYSIWYG designers right now. That said F# is targeted more at code-orientated developers and I’ve rarely seen a developer use a designer for XAML, everyone seems to end up editing the XML directly.

Emulators

Once you’re up and running, which doesn’t take long, you can run your code at one of the supplied Android emulators or connect your device:

Xamarin Android emulator running on Mac

And of course you can debug live code running in the Android emulator:

Debug FSharp Code running on Android in Xamarin Studio on Mac

Nexus 7

Here’s my “hello world” bubbles app running on my Nexus 7:

Bubbles on Nexus 7

Tutorials

Neil Danson gave a great introduction to F# on iOS at Skills Matter recently:

Including a mini-game imaginatively titled Pissed Off Owls.

The experience for iOS and Android are pretty similar.

Neil also has a set of tutorials on F# and MonoGame:

If you’re interested in meeting the man behind Xamarin why not pop over to the Progressive F# Tutorials in New York on September 18th and 19th:

rev-progfsharpnyc-800x300px

5 Common C# Misconceptions

I’ve had the pleasure of working with and interviewing C# developers for over a decade now. However here’s 5 common misconceptions I continue to encounter.

1) Lists are implemented as linked lists

List<T> is actually implemented using an underlying array. The name is a little misleading with the earlier non-generic version having the less ambiguous name of ArrayList and in F# they are aliased to ResizeArray to avoid confusion. Needless to say the performance characteristics of operations on an array are somewhat different to those of a linked list.

2) var is dynamic

The var keyword is used to implicitly define a local variable that is strongly typed using type inference.There is actually no runtime difference from explicitly defining the type.

3) Dependency injection requires interfaces

Dependency injection has become common practice in C# code bases. Many seem to believe that you can only inject interfaces, often leading to interface proliferation, to the point that it can feel like you’re back in C++ land with header files. In fact most dependency injection environments support injection of abstract and even concrete classes.

4) Built-in serialization is efficient

The truth is the opposite, it is slow and verbose. If you’re looking for something efficient consider using Google Protocol Buffers with a library like protobuf-net or JSON from a third party like Service Stack.

5) C# is at the cutting edge of programming language design

C# is heavily based on the Java programming language, and has since made some incremental improvements like LINQ and more recently the async/await keywords. The reality is that all of the “new” features in C# are actually rather old, and progress has been pretty slow when compared to more recent curly brace languages like Scala and Nemerle.

Iterators introduced in C# in 2005 are merely coroutines, defined in 1963, they were first seen in the 1970s in Modula-2.

LINQ provides a library of higher order functions available as extension methods. Similar libraries have been available in functional programming languages like ML since the 70s, for example Select is equivalent to List.map and Where is equivalent to List.filter.

Finally C#’s innovative new async feature actually first appeared in F# back in 2007.

Maybe the pace will pick up when Roslyn is finally delivered, but if you want to experience a wider range of features you might want to look at Clojure, F#, Nemerle, Scala or TypeScript.

Generative Art

Last night I ran a free hands on Generative Art session to a full class room at Skills Matter for the F#unctional Londoners meetup group. We host a hands on programming sessions every month, next month we’ll return to the Machine Learning theme with Matt Moloney from the Tsunami IDE team.


Samples: http://trelford.com/GenerativeArt.zip

I recently picked up Matt Pearson’s Generative Art book published by Manning, his examples use the Processing programming language which is loosely based on Java. For the hands on creative part we used F# and the SmallSharp library which has a similar feel but is limited to 2D.

SmallSharp

SmallSharp is a small .Net library for drawing graphics, similar to Small Basic but aimed more at the "Sharp" languages C# and F#

Small Basic the good parts:

  • minimal IDE: you get intellisense, buttons for opening and saving files and a big run button (F5)
  • simple library: type GraphicsWindow and dot to start drawing shapes, no need worry about Single Threaded Apartments, data binding or XAML
SmallBasic

Small Basic’s library is just about usable from C# and F# but relies on strings and implicit conversions to a variant type, where as SmallSharp’s API takes explicit typed arguments.

In F# with SmallSharp we can write:

GraphicsWindow.BrushColor <- red
for i in 0..5..200 do
    GraphicsWindow.DrawLine(i,0,200-i,200)
    GraphicsWindow.DrawLine(0,i,200,200-i)

 

Which draws concentric lines:

Pattern

Bubbles

I found a nice piece on Deviant Art entitled Bubbles:

colorful_bubbles_by_basil4life-d6i06vv

The task was to generate a similar work, starting with the following code:

Win.Background <- black
let rand = System.Random()
let colors = [red; green; blue; yellow]
for i = 1 to 200 do
    Win.Opacity <- rand.NextDouble() ** 3.0
    Win.FillColor <- colors.[rand.Next(colors.Length)]
    let x = rand.NextDouble() * Win.Width
    let y = rand.NextDouble() * Win.Height
    let r = 10.0 + rand.NextDouble() * 30.0
    Win.DrawEllipse(x-r,y-r,r*2.0,r*2.0)

Here’s a monochrome from David Kowalski:

Monochrome

and an interesting Spiral effect from Rob Lyndon:

Spiral Galaxy

FunScript

Following Atwood's Law:

any application that can be written in JavaScript, will eventually be written in JavaScript.

I created the same effect using the HTML5 Canvas, with the F# code being compiled to JavaScript by the FunScript library, which also gives typed access to JavaScript libraries.

[<ReflectedDefinition>]
module Program

open FunScript
open FunScript.TypeScript

type ts = Api<"../Typings/lib.d.ts">

let circle (ctx:ts.CanvasRenderingContext2D) (x,y,d,c) =
   let pi = ts.Math.PI
   ctx.beginPath()
   ctx.arc(x, y, d, 0.0, pi * 2.0)
   ctx.fillStyle <- c
   ctx.fill()   

let inline str x = x.ToString()
let rgba (r,g,b) a = "rgba("+str r+","+str g+","+str b+","+str a+")";
let next n = ts.Math.random() * n
let from n = ts.Math.floor(next (float n)) |> int

let main() =
   let canvas = unbox<ts.HTMLCanvasElement>(ts.document.getElementById("canvas"))
   canvas.width <- 1000.
   canvas.height <- 500.
   let ctx = canvas.getContext("2d")
   // Set background
   ctx.fillStyle <- "rgb(0,0,0)"
   ctx.fillRect (0., 0., canvas.width, canvas.height);
   /// Circle colors
   let colors = [
      255,0,0
      0,255,0
      0,0,255
      255,255,0
      ]
   // Draw circles
   for i = 1 to 200 do
      let x = next canvas.width
      let y = next canvas.height
      let r = 10. + next 40.
      let a = next 1.
      let c = rgba (colors.[from colors.Length]) a
      circle ctx (x, y, r, c)

Circles


Turing Drawings

We finished up on drawing roulette with Turing drawings, made by random Turing machines:

DrawingRoulette

I created an F# version a few weeks back which you can run in the Cloud Tsunami IDE.

Have fun!