Friday, 11 October 2013

Scribble app in 12 lines of F#

Here’s a little Scribble app for F# Interactive in just 12 lines of code:

#r "PresentationCore"
#r "PresentationFramework"

open System.Windows

let canvas = Controls.Canvas()
let window = Window(Content=canvas)
let mutable lines = Shapes.Polyline()
window.MouseDown.Add(fun _ ->
  lines <- Shapes.Polyline(Stroke=Media.Brushes.Black, StrokeThickness=1.0)
  ignore(canvas.Children.Add lines))
window.MouseMove.Add(fun e -> lines.Points.Add(e.GetPosition window))
window.MouseUp.Add(fun _ -> lines <- Shapes.Polyline())
Application().Run window

This program begins by referencing the required WPF assemblies and opening a namespace. The canvas and a window containing it are created followed by a mutable global polyline. The mouse down event causes the polyline to be replaced and the new one added to the canvas. The mouse move event causes the current mouse position to be appended to the end of the points on the current polyline. The mouse up event replaces the polyline but does not add the new one to the canvas.

The result looks like this:

If you want to see more F# programs, subscribe to the F# Journal today!

No comments: