I was working on a UI project which involves WPF/Metro command binding. The ICommand interface requires two functions: CanExecute and Execute. Because I already have some functions implemented in the F# project, I'd image implement ICommand in F# project is much easier.
In the WPF converter code snippets, I defined a new type to represent the converter. The code is like:
type StringToVisiblityConverter() = inherit ConverterBase(stringToInt>>intToBool>>boolToVisibility |> convert, nullFunction)
This technique is very familiar to C# developer. But I do not like the way the code, especially the inherit ConverterBase. What I really want to say is: create a command with two functions. I ended up with the code like the following:
let createCommand action canExecute=
let event1 = Event<_, _>()
new ICommand with
member this.CanExecute(obj) = canExecute(obj)
member this.Execute(obj) = action(obj)
member this.add_CanExecuteChanged(handler) = event1.Publish.AddHandler(handler)
member this.remove_CanExecuteChanged(handler) = event1.Publish.AddHandler(handler)
let myCommand = createCommandcreateCommand is a template function which takes two functions as input parameter. This function returns a ICommand object. The myCommand takes two dummy functions and generate a concrete object. I can reference this myCommand object from C# without any problem and the code is more readable than C# version.
(fun _ -> ())
(fun _ -> true)
As a professional developer, I am interested any technique can make my code more readable. How about you? :-)