Phil Trelford's Array
POKE 36879, 255

PacMan Kata

January 11, 2012 11:37 by phil

F#unctional LondonersThe F#unctional Londoners Meetup Group will be starting 2012 with a code Kata on Thursday January 26th at 6:30pm at Skills Matter.

 
Kata

The term Kata comes from martial arts. A code Kata is a short programming exercise for practicing an aspect of software development.

C64_explodingfistBack in November in the Programming with the Stars session at the Progressive F# Tutorials our celebrities Mark Needham and Mark Seemann took on the Tennis Kata, first in C# and then F#.

As the two Mark’s talked through their solutions a number of people worked on their own versions, 2 of which you can see on the F# Snippets site:


PacMan
Scanning over the Kata catalogue for ideas the PacMan Kata bit me immediately.

    Pacman finds himself in a grid filled with monsters. Will he be able to eat all the dots on the board before the monsters eat him?

    maze

    To get things started I’ve built up a maze and some graphics. You can see an example over on F# Snippets that runs in the browser on http://tryfsharp.org which uses Silverlight: PacMan Maze

    I’ve also created a repository on BitBucket with sample projects for Visual Studio 2010 targeting WPF, Silverlight and HTML/JavaScript.

    The Javascript version uses the Pit compiler, you can see it running here. (Keys Q/A/Z/X *only in IE)

     


    Look forward to seeing you at the event.


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

    Mini Rx: Observable Extensions

    October 31, 2011 12:47 by phil

    The Reactive Extensions (Rx) provide LINQ style querying capabilities for events in C#, VB.Net and JavaScript. Rx implements extension methods over IObservable<T>, just as LINQ to Objects provides a set of extension methods over IEnumerable<T>,

    ReactiveExtensions4dotNet

    There has been a fair amount of Microsoft publicity on the Rx library in blogs, videos and talks. Demand for Rx skills in IT jobs has grown over the last 12 months. 

    Reactive Extensions Demand Trend

    That said, the current implementation of the Rx library has at least a couple of issues:

    Given that LINQ is based partly on higher-order functions from functional programming perhaps it’s not surprising F# supported querying over events back in 2006. It’s also relatively trivial to expose this functionality to C# by defining compatible extension methods using the ExtensionAttribute e.g.

    [<Extension>]
    type ObservableExtensions private () =
       [<Extension>]
       static member Select<'T,'U>(source:IObservable<'T>,selector:Func<'T,'U>) =
           source |> Observable.map selector.Invoke
       [<Extension>]
       static member Where<'T>(source:IObservable<'T>,predicate:Func<'T,bool>) =
           source |> Observable.filter predicate.Invoke
       [<Extension>]
       static member Subscribe<'T>(source:IObservable<'T>, action:Action<'T>) =
           source |> Observable.subscribe action.Invoke

    This is already enough to provide basic LINQ syntax in C# for types implementing IObservable<T>:

    var leftPressedMove =
        from e in mouseMove
        where e.LeftButton == MouseButtonState.Pressed
        select e;

    F# custom events implement IObservable<’T> by default and F# provides modules with higher-order functions for both .Net Events and the IObservable<’T> interface.

    For C# a mechanism is needed to convert .Net events to an object that implements IObservable<T>. This can be achieved fairly concisely in F# using object expressions:

    let FromEvent<'TEventArgs, 'TDelegate when 'TEventArgs:> EventArgs>
        (conversion:Func<Action<'TEventArgs>,'TDelegate>,
            addHandler:Action<'TDelegate>,
                removeHandler:Action<'TDelegate>)  =
        { new IObservable<'TEventArgs> with
            member this.Subscribe(observer:IObserver<_>) =
                let handler = Action<_>(observer.OnNext) |> conversion.Invoke
                addHandler.Invoke handler
                let remove () = removeHandler.Invoke handler
                { new IDisposable with member this.Dispose() = remove () }
        }

    Although converting from the event in C# feels a little convoluted:

    var mouseMove =
        Observable.FromEvent<MouseEventArgs, MouseEventHandler>(
            f => new MouseEventHandler((sender, args) => f(args)),
            handler => MouseMove += handler,
            handler => MouseMove -= handler);

    Again for C# a mechanism is required for directly creating objects that can be both a source of events and be used to observe events. Rx follows the Observer pattern and provides a type called Subject that implements both IObserver<T> and IObservable<T>.

    Earlier in the year I put up 2 simple types on F# Snippets, that are functionally equivalent to Rx’s Subject<T> and ReplaySubject<T>:

    The ReplaySubject implementation uses F# Agents to simplify concurrency..

    The types can be used easily from C#:

    var s = new Subject<int>();
    s.Subscribe(Console.WriteLine);
    s.OnNext(1);

    For Silverlight and WPF we need a mechanism for invoking methods on the UI thread, which I implemented in F# back in 2010: Implementing IObservable and extending Observable 

    mouseMove
        .Select(e => e.GetPosition(canvas))
        .Delay(closure * 100)
        .OnDispatcher()
        .Subscribe(pos =>
        {
            Canvas.SetLeft(label, pos.X + closure * 10);
            Canvas.SetTop(label, pos.Y);
        });

    Putting it altogether, the inevitable "time flies like an arrow" Silverlight demo:


    In case you’d like to have a play yourself, I’ve put up a preview release on CodePlex:

    http://minirx.codeplex.com/


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

    Exposing F# Dynamic Lookup to C#, WPF & Silverlight

    May 23, 2010 15:20 by phil

    Like C#, F# is primarily a statically typed programming language. That said both languages provide support for dynamic typing.

    Sometimes dynamic typing can be a pragmatic way of solving a specific problem. For example say you’re a solutions provider with a core product and have a number of clients with bespoke requirements. One client asks for a product rating feature. This can be relatively easily achieved using dynamic properties:

    • a bunch of client specific properties are read from the database, including the rating value, which is then set as a dynamic property on the product object
    • zero changes are required to the core code
    • at the UI, on WPF, the dynamic property can simply be bound through XAML like any other object property
    • on Silverlight 4,0 direct binding is not currently possible, however there is a simple workaround - specifying the dynamic property as a parameter for a value converter (example later)

    C# and F# use slightly different approaches for dynamic properties:

    • C# 4.0 provides a dynamic type, which tells the compiler that member lookup on the object should be deferred to run time
    • F# employs a dynamic lookup operator, which when overloaded defines the behaviour at runtime. This means that in F# dynamic lookup is explicit (the ? operator), and can be mixed with static lookup on the same object (the . operator)

    Is it is still possible to implement dynamic properties in F# that can be consumed by other .Net languages like C#, VB.Net, IronRuby or IronPython; plus WPF and Silverlight. The trick is to inherit from .Net 4.0’s System.Dynamic.DynamicObject type and implement the System.ComponentModel.INotifyPropertyChanged interface:

    open System.Dynamic
    
    
    /// Dynamic Lookup type
    type DynamicLookup () =
        inherit DynamicObject ()
        /// Synchronization object
        let sync = obj()
        /// Property Changed event
        let propertyChanged = Event<_,_>()    
        /// Properties
        let mutable properties = Map.empty
        /// Gets property value
        member private this.GetValue name = 
            Map.tryFind name properties
        /// Sets property value, creating a new property if none exists
        member private this.SetValue (name,value) =
            /// Atomically writes new properties reference
            let Write () = 
                properties <-
                    properties 
                    |> Map.remove name 
                    |> Map.add name value
            // Synchronize property writes
            lock sync Write
            // Trigger property changed event
            (this,System.ComponentModel.PropertyChangedEventArgs(name))
            |> propertyChanged.Trigger    
        override this.TryGetMember(binder:GetMemberBinder,result:obj byref ) =     
            match this.GetValue binder.Name with
            | Some value -> result <- value; true
            | None -> false
        override this.TrySetMember(binder:SetMemberBinder, value:obj) =        
            this.SetValue(binder.Name,value)
            true
        override this.GetDynamicMemberNames() =
            properties |> Seq.map (fun pair -> pair.Key)
        [<CLIEvent>]
        member this.PropertyChanged = propertyChanged.Publish
        interface System.ComponentModel.INotifyPropertyChanged with
            [<CLIEvent>]
            member this.PropertyChanged = propertyChanged.Publish     
        static member (?) (lookup:#DynamicLookup,name:string) =
            match lookup.GetValue name with
            | Some(value) -> value
            | None -> raise (new System.MemberAccessException())        
        static member (?<-) (lookup:#DynamicLookup,name:string,value:'v) =
            lookup.SetValue (name,value)
        static member GetValue (lookup:DynamicLookup,name) =
            lookup.GetValue(name).Value

    F# usage:

    /// Product type inherits dynamic lookup
    type Product (name,price) =
        inherit DynamicLookup ()
        member this.Name = name
        member this.Price = price
     
    // Initiate product object with dynamic rating value
    let p = Product("F# for Scientists",49.95M)
    do p?Stars <- 5
    // Access product's properties
    let stars = System.Convert.ToInt32(p?Stars)
    do printf "%s...%M %s" p.Name p.Price (System.String('*',stars))

    C# usage:

    // Create Product type with dynamic stars value
    Product product = new Product("Expert F#",54.99M);
    ((dynamic)product).Stars = 5;       
    // Read product properties
    dynamic p = product;
    string s = 
        string.Format("{0}...{1} {2}",
            p.Name, p.Price, new String('*', (int) p.Stars));

    Use from Silverlight 4.0

    <t:PropertyLookup x:Key="DynamicConverter"/>
    

     

    <TextBox Text="{Binding Converter={StaticResource DynamicConverter},
                    ConverterParameter=Stars}"/>
    

     

    dynamic product = new Product("Real World FP", 35.99);
    product.Stars = 5;
    DataContext = product;

     

    public class PropertyLookup : IValueConverter
    {
        public object Convert(
            object value, 
            Type targetType, 
            object parameter, 
            CultureInfo culture)
        {        
            return DynamicLookup.GetValue(
                (DynamicLookup) value,
                (string) parameter);            
        }
    
        public object ConvertBack(object value, 
            Type targetType, 
            object parameter, 
            CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    Note: Silverlight 4.0 requires Microsoft.CSharp.dll to use dynamic types.


    Tags:
    Categories: F# | WPF | Silverlight | Architecture | .Net | C#
    Actions: E-mail | Permalink | Comments (3) | Comment RSSRSS comment feed