Phillip Trelford's Array

POKE 36879,255

Silverlight 4 Calculator Sample in F#

If you have Silverlight 4 installed you should see a calculator sample below coded in F#. The sample originally targeted WPF, only a few modifications were required to run in Silverlight:

  • the view is hosted in a UserControl instead of a Window
  • a C# project is used to launch the UserControl and generate the Silverlight XAP file

The sample demonstrates creating a View in WPF or Silverlight without XAML. The idea is to make things a little easier from F# by implementing a (+) operator overload to attach dependency properties.

The following snippet shows the keypad being constructed by transforming tuples describing the key character and action to buttons:

let keys =
    let grid = new Grid()
    for i = 1 to 4 do
        ColumnDefinition() |> grid.ColumnDefinitions.Add 
        RowDefinition() |> grid.RowDefinitions.Add
    [ 
    ['7',Digit(7);'8',Digit(8);'9',Digit(9);'/',Operator(Divide)]
    ['4',Digit(4);'5',Digit(5);'6',Digit(6);'*',Operator(Multiply)]
    ['1',Digit(1);'2',Digit(2);'3',Digit(3);'-',Operator(Minus)]
    ['0',Digit(0);'.',Dot;'=',Evaluate;'+',Operator(Plus)]
    ]    
    |> List.mapi (fun y ys ->
        ys |> List.mapi (fun x (c,key) ->
            let color =
                match key with
                | Operator(_) | Evaluate -> Colors.Yellow
                | Digit(_) | Dot -> Colors.LightGray                        
            let effect =
                Binding("Operator",
                        Converter=operationEffectConverter,
                        ConverterParameter=key)    
            Button(Content=c,CommandParameter=key,
                Width=40.0,Height=40.0,Margin=Thickness(4.0),
                Background=SolidColorBrush(color)) +                
                Button.CommandBinding(Binding("KeyCommand")) +
                Button.EffectBinding(effect) +
                Grid.Column(x) + Grid.Row(y)                         
        )
    )
    |> List.concat
    |> List.iter (grid.Children.Add >> ignore)
    grid

 

Note: This article is more a thought experiment in trying F# code instead of XAML to describe a View. In many cases XAML with a C#/F# View Model may be the pragmatic choice.

PS There is a very concise WebSharper F# Calculator sample, that generates JavaScript.

SilverlightCalculator.zip (10.09 kb)

Runtime Units of Measure for F#

The F# compiler includes a Units of Measure feature which infers a measure type at compile time, which means you get measure type safety with uncompromised runtime performance.

Example of F#’s built-in Units of Measure feature (hover over shows inferred type):

metres per second

Sometimes you might also want to actually infer units of measure at runtime, say to display the inferred unit type at the UI. The following F# code prototype provides such inference.

Lets start by defining some metres and seconds unit types:

let m = UnitType.Create("m")
let s = UnitType.Create("s")

Now with the source below we can explore types in F# Interactive:

> 10.0 * m;;
val it : UnitValue = 10 m {Unit = Unit ("m",1);
                           Value = 10.0;}
> 10.0 * m / 5.0 * s;;
val it : UnitValue = 2 m s {Unit = CompositeUnit [Unit("m",1); Unit("s",1)];
                            Value = 2.0;}

Source code to F# runtime units of measure:

type UnitType =
    | Unit of string * int 
    | CompositeUnit of UnitType list     
    static member Create(s) = Unit(s,1)
    override this.ToString() =
        let exponent = function
            | Unit(_,n) -> n
            | CompositeUnit(_) ->                
                raise (new System.InvalidOperationException())
        let rec toString = function        
            | Unit(s,n) when n=0 -> ""
            | Unit(s,n) when n=1 -> s
            | Unit(s,n)          -> s + " ^ " + n.ToString()            
            | CompositeUnit(us) ->               
                let ps, ns = 
                    us |> List.partition (fun u -> exponent u >= 0)
                let join xs = 
                    let s = xs |> List.map toString |> List.toArray             
                    System.String.Join(" ",s)
                match ps,ns with 
                | ps, [] -> join ps
                | ps, ns ->
                    let ns = ns |> List.map UnitType.Reciprocal
                    join ps + " / " + join ns
        match this with
        | Unit(_,n) when n < 0 -> " / " + toString this
        | _ -> toString this    
    static member ( * ) (v:ValueType,u:UnitType) = UnitValue(v,u)    
    static member ( * ) (lhs:UnitType,rhs:UnitType) =
        let text = function
            | Unit(s,n) -> s
            | CompositeUnit(us) -> us.ToString()
        let normalize us u =
            let t = text u
            match us |> List.tryFind (fun x -> text x = t), u with
            | Some(Unit(s,n) as v), Unit(_,n') ->
                us |> List.map (fun x -> if x = v then Unit(s,n+n') else x)                 
            | Some(_), _ -> raise (new System.NotImplementedException())
            | None, _ -> us@[u]
        let normalize' us us' =
            us' |> List.fold (fun (acc) x -> normalize acc x) us
        match lhs,rhs with
        | Unit(u1,p1), Unit(u2,p2) when u1 = u2 ->
            Unit(u1,p1+p2)        
        | Unit(u1,p1), Unit(u2,p2) ->            
            CompositeUnit([lhs;rhs])
        | CompositeUnit(us), Unit(_,_) ->
            CompositeUnit(normalize us rhs)
        | Unit(_,_), CompositeUnit(us) ->
            CompositeUnit(normalize' [lhs]  us)
        | CompositeUnit(us), CompositeUnit(us') ->
            CompositeUnit(normalize' us us')
        | _,_ -> raise (new System.NotImplementedException())
    static member Reciprocal x =
        let rec reciprocal = function
            | Unit(s,n) -> Unit(s,-n)
            | CompositeUnit(us) -> CompositeUnit(us |> List.map reciprocal)
        reciprocal x
    static member ( / ) (lhs:UnitType,rhs:UnitType) =        
        lhs * (UnitType.Reciprocal rhs)
    static member ( + ) (lhs:UnitType,rhs:UnitType) =       
        if lhs = rhs then lhs                
        else raise (new System.InvalidOperationException())
and ValueType = float
and UnitValue(v:ValueType,u:UnitType) = 
    member this.Value = v 
    member this.Unit = u
    override this.ToString() = sprintf "%O %O" v u
    static member (+) (lhs:UnitValue,rhs:UnitValue) =
        UnitValue(lhs.Value+rhs.Value, lhs.Unit+rhs.Unit)         
    static member (*) (lhs:UnitValue,rhs:UnitValue) =                    
        UnitValue(lhs.Value*rhs.Value,lhs.Unit*rhs.Unit)                
    static member (*) (lhs:UnitValue,rhs:ValueType) =        
        UnitValue(lhs.Value*rhs,lhs.Unit)      
    static member (*) (v:UnitValue,u:UnitType) = 
        UnitValue(v.Value,v.Unit*u)  
    static member (/) (lhs:UnitValue,rhs:UnitValue) =                    
        UnitValue(lhs.Value/rhs.Value,lhs.Unit/rhs.Unit)
    static member (/) (lhs:UnitValue,rhs:ValueType) =
        UnitValue(lhs.Value/rhs,lhs.Unit)  
    static member (/) (v:UnitValue,u:UnitType) = 
        UnitValue(v.Value,v.Unit/u)


Implementation details:

Unit (UnitType) computations are separate from value (UnitValue) computations. A single unit types (say metres) just has a name and a power (default of 1):

let metres = Unit(name = “metres”, power = 1)

To multiply by the same unit type, simply add the powers:

(2.0 * metres) * (3.0 metres) = 6.0 metres ^ 2

To handle composite unit types, when multiplying 2 unit values, first try to find a matching unit type in the existing list, if successful add the powers, otherwise add the new type:

2.0 * metres * seconds = 2 .0 metres (per) second

To divide simply multiply by the reciprocal:

(2.0 * metres * seconds) / (1.0 * seconds) = 2.0 metres per second * 1.0 seconds ^ -1

Resources:

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

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.