Skip to content

Rick Minerich's Development Wonderland

These are the stories that have been posted to the Rick Minerich's Development Wonderland blog.

Steepest Ascent Hill Climbing in C# and F#


Published to Rick Minerich's Development Wonderland by Richard Minerich December 28, 2009 19:21

Recently I’ve been working with some local search techniques and wanted to share my Steepest Ascent Hill Climbing solution.

The general idea of Steepest Ascent Hill Climbing is that in each iteration of the hill climbing process you apply a set of transforms to your input data and select the best result via a fitness function.  This result, or the transform which created it, is then the input for your next iteration.  The process stops when no transform in an iteration scored higher than the previous generation’s winner.

In this way each iterative step brings you closer to a local maxima of your fitness function’s graph.  This is where the term “Hill Climbing” comes from.  It is considered a relatively simple AI technique but is also is broadly applicable, quite easy to reason about and can be tweaked for many different corner cases.

For this particular example we will be assuming composable transforms.  For each iteration of our hill climbing we will apply our standard transform set to the winning transform of the last round and so produce a new set of transforms.  

public delegate T TransformComposer<T>(T lastT, T thisT);
public delegate S TransformApplier<S, T>(S set, T transform);
public delegate uint FitnessFunction<S>(S set);

public class HillClimberResult<S, T>
{
    public HillClimberResult(uint score, T transform, S set)
    {
        Score = score;
        Transform = transform;
        Set = set;
    }

    public uint Score { get; private set; }
    public T Transform { get; private set; }
    public S Set { get; private set; }
}

public class HillClimber<S, T>
{
    public HillClimber(
      TransformComposer<T> composer,
      TransformApplier<S, T> applier,
      FitnessFunction<S> fitness)
    {
        TransformComposer = composer;
        TransformApplier = applier;
        FitnessFunction = fitness;
        Transforms = new List<T>();
    }

    public List<T> Transforms { get; private set; }

    private TransformComposer<T> TransformComposer { get; set; }
    private TransformApplier<S, T> TransformApplier { get; set; }
    private FitnessFunction<S> FitnessFunction { get; set; }

    public HillClimberResult<S, T> FindMaxima(S inputSet, T initialTransform)
    {
        if (inputSet == null)
            throw new ArgumentNullException("inputSet");
        if (initialTransform == null)
            throw new ArgumentNullException("initialTransform");
        if (Transforms.Count == 0)
            throw new ArgumentException("No transforms were set.");

        HillClimberResult<S, T> best;
        HillClimberResult<S, T> iterBest = ApplyTransformAndScore(inputSet, initialTransform);

        do
        {
            best = iterBest;
            foreach (T transform in Transforms)
            {
                var nextTransform = TransformComposer(best.Transform, transform);
                var result = ApplyTransformAndScore(inputSet, nextTransform);
                if (iterBest.Score < result.Score)
                    iterBest = result;
            }
        } while (iterBest.Score > best.Score);

        return best;
    }

    private HillClimberResult<S, T> ApplyTransformAndScore(S inputSet, T transform)
    {
        var transformedSet = TransformApplier(inputSet, transform);
        var score = FitnessFunction(transformedSet);
        return new HillClimberResult<S, T>(score, transform, transformedSet);
    }
}

 

I like the way this worked out in C# quite a lot.  However, take a moment to compare it to a F# version I quickly whipped up: 

type HillClimber(composer, applier, fitness, transforms) =
    member x.FindMaxima initialSet initialTransform =
        let maxOfScores one two = if fst one > fst two then one else two
        let findBestTransform set lastTransform =
          transforms
            |> List.map (fun(transform) -> composer lastTransform transform)
            |> List.map (fun(transform) -> applier set transform, transform)
            |> List.map (fun(transformedSet, transform) -> (fitness transformedSet), transform)
            |> List.reduce maxOfScores
        let rec climb set lastScore lastTransform =
            let (thisScore, thisTransform) = findBestTransform set lastTransform
            if thisScore <= lastScore then (lastScore, lastTransform)
            else climb set thisScore thisTransform
        climb initialSet (fitness initialSet) initialTransform

 

It’s quite shocking how much less code is necessary.   However, there is a small problem with this example.  As we are not using HillClimber from inside of its own library, all of its function inputs resolve to System.Object. The solution is to simply do a bit of annotating to ensure that compile time types are as generic as possible.

type TransformComposer<'t> = 't -> 't -> 't
type TransformApplier<'s,'t> = 's -> 't -> 's
type FitnessFunction<'s> = 's -> float
  
type HillClimber<'s,'t>(composer: TransformComposer<'t>, applier: TransformApplier<'s,'t>, fitness: FitnessFunction<'s>, transforms: list<'t>) =
    member x.FindMaxima initialSet initialTransform =
        let maxOfScores one two = if fst one > fst two then one else two
        let findBestTransform set lastTransform =
          transforms
            |> List.map (fun(transform) -> composer lastTransform transform)
            |> List.map (fun(transform) -> applier set transform, transform)
            |> List.map (fun(transformedSet, transform) -> (fitness transformedSet), transform)
            |> List.reduce maxOfScores
        let rec climb set lastScore lastTransform =
            let (thisScore, thisTransform) = findBestTransform set lastTransform
            if thisScore <= lastScore then (lastScore, lastTransform)
            else climb set thisScore thisTransform
        climb initialSet (fitness initialSet) initialTransform

 

Of course,  it would be great if the F# type system would reduce to generics instead of System.Object in this case.  I would think the ideal would be to always reduce to the most generic type possible.  I’ll have to give it a try tonight with the latest VS2010 beta and see if there is any improvement.

Continuing on, let’s give this a go with something simple.  We know that the maximum value of |A| – A^2 is 0.5, –0.5.  Can we climb our way to one of these values?

#load "HillClimber.fs"
open HillClimber

let composer last next = fun x -> (last x) + (next x)
let applier set transform = transform set;
let fitness x = abs( x ) - (x ** 2.0)
let transforms = [fun x -> x + 1.0;
                  fun x -> x - 1.0;
                  fun x -> x + 0.1;
                  fun x -> x - 0.1;
                  fun x -> x + 0.01;
                  fun x -> x - 0.01]

let climber = new HillClimber<float,float->float>(composer, applier, fitness, transforms)

let initialValue = 0.0
let (score, transform) = climber.FindMaxima initialValue (fun x -> x)
let result = transform initialValue

…Highlight, Alt-Enter…

val composer : ('a -> float) -> ('a -> float) -> 'a -> float
val applier : 'a -> ('a -> 'b) -> 'b
val fitness : float -> float
val transforms : (float -> float) list =
  [<fun:transforms@10>; <fun:transforms@11-1>; <fun:transforms@12-2>;
   <fun:transforms@13-3>; <fun:transforms@14-4>; <fun:transforms@15-5>]
val climber : HillClimber.HillClimber<float,(float -> float)>
val initialValue : float = 0.0
val transform : (float -> float)
val score : float = 0.25
val result : float = -0.5

Looks good!

 

Well, it looks like that took a bit longer than I had anticipated.  I’ll be back with my weekly update tomorrow.

F# Discoveries This Week 12/14/2009


Published to Rick Minerich's Development Wonderland by Richard Minerich December 14, 2009 16:06

An almost overwhelming number of posts this week with topics including the Skills Matter Programming Exchange, LAgent, data structures, service oriented architecture, monads, infinite sequences, timing F# functions, functional design, and much more.  Come in and check it out.

 

Don Syme on WebSharper: F#-based Rich Client/Server Web Applications

Intellifactory seem to have set about answering the question of "just how simple, clean and productive can you make developing rich web applications that target Javascript?" (my words, not theirs).  While still in beta, signs are that Intellifactory are putting together an impressive technology that makes really good use of F#'s unique facilities to simplify this class of applications.

 

Mike Hadlow on the Skills Matter Functional Programming Exchange

I had a great time today at the Functional Programming Exchange organised by Robert Pickering and Skills Matter. Robert managed to grab some really interesting speakers who gave a nice snapshot of the current art and use of FP.

 

Luca Bolognese on LAgent: an agent framework in F# – Part X – ActiveObject

So you start thinking if there is a way to enhance vanilla objects to make them agents. You want to reuse all the concepts that you are familiar with (i.e. inheritance, visibility rules, etc…) and you want your clients to call agents as if they were calling normal objects. Obviously, under the cover, the method calls won’t execute immediately, but they would be queued.

 

Ted Neward’s A New Kind of Service

Why study new and different programming languages? To change your programming mindset. Not sure what I mean by that? Check this out.

 

Anton Tayanovskyy on Generic Workflow Builders (Monads) in F#

This blog post is about a quick and dirty encoding of Haskell type classes in F#. With the ongoing work on the WebSharper™ project, we are currently very interested in coaxing the .NET type system to support writing code that is generalized over monads and applicative functors.

 

Anton Tayanovskyy on Foldr or FoldBack on Infinite F# Sequences

A noticeable omission in F# standard library is Seq.foldBack, or the famous Haskell foldr. The semantics of foldr is very simple to remember: it replaces the native cons and nil of a list with arbitrary computations.

 

Anton Tayanovskyy on The Execution Speed of Early vs Late Binding

This little post documents one of my little experiments with F#, as I am educating myself on the .NET Framework fundamentals.

This post is also interesting because it describes how to turn on timing in F# interactive.

 

Julien Ortin’s Purely Functional Data Structures in F#: Batched Queue, Binomal Heap and Red-black Set

This post describes the F# implementation of the <insert data structure here> from Chris Okasaki’s “Purely functional data structures”.

 

Justin Lee’s Infer.NET – Now with F# Support

Infer.NET is a framework for running Bayesian inference in graphical models. You can use it to solve many different kinds of machine learning problems, from standard problems like classification or clustering through to customised solutions to domain-specific problems.

 

Joh’s Inheritance Nightmares

At this point, readers interested in F# and functional programming languages might wonder what all this has got to do with F#. I think that the common mix of mutability and inheritance is not a very strong basis for good software design. I never really realized that until I took a look at functional programming and immutability.

 

Talbott Crowell’s Slides from Parallel and Concurrent Programming with F#

As promised, please find the slides and source code for the demos.

 

Ryan Riley Discusses F# on the HighOnCoding Podcast

Last week I had the pleasure of recording a podcast with Ryan Riley about F# programming language. Ryan discussed different features of the F# language and how it can be used to build applications.

 

Cameron Taggart’s F# on Mac using Cocoa

Laurent Etiemble created a Monobjc project/library that allows access to Objective-C frameworks and libraries like Cocoa.  I just ported the first tutorial to F#.  I’m able to build it on my PC and run it on my Mac.

 

Mark Needham’s Haskell vs F#: Function Composition

I'm reading through John Hughes' 'Why functional programming matters' paper and one thing I've come across which is a bit counter intuitive to me is the Haskell function composition operator.

 

Marius Bancila’s F# Operations on List

In this post I want to show how you can implement common list operations: union, intersection, difference and concatenation.

 

Viabhav Bhandari’s F# – Functional Approach

In this version of interesting programming concepts, I would like to highlight type system based pattern matching available in F#/OCAML, its very unique and extremely useful if you are parsing a structured list or working on a symbol table.

F# Discoveries This Week 02/08/2010


Published to Rick Minerich's Development Wonderland by Richard Minerich February 08, 2010 19:28

Back again with another F# community roundup.   There’s been a ton of great content this week, almost too much.  To try to combat this I’ve attempted to sort posts roughly in terms of how interesting I found them.  All were worth the read though.

Also, I’ll be speaking this Wednesday on F# at the Boston .NET User Group.  If you find yourself there, be sure to say hello!

 

Don Syme’s Introduction to F# (Video 1 of 3)

Dr. Don Syme is a principal researcher in MSR Cambridge. He has a rich history in programming language research, design, and implementation (C# generics being one of his most recognized implementations), and is the principle creator of F#.

 

Ashley Feniello’s FScheme Part 8: Language vs. Library

Perhaps this post should have gone along with the one about macros and how Lisp is a “programmable programming language.” The common tension in any language or runtime design is how much to build in as primitives and how much to implement as libraries within the language or atop the runtime.

 

Luke Hoban’s F# for Parallel and Asynchronous Programming

Last November at PDC 2009 in Los Angeles I gave a talk on F# for Parallel and Asynchronous Programming.  The talk begins by covering basic F# concepts, and then focuses on four challenging issues related to concurrency and the tools F# brings for addressing these - immutability, async workflows, and agents.

 

Andrew Brehaut’s On Iteration (Could just as well be entitled “Why Programmers Leave Python/C#/Java")

There is an observable trend in Python programmers that results in a reasonable section of them moving to functional programming languages. This trend is encouraged by the Python language, and has a couple of temporal considerations.

 

Matthew Podwysocki’s Using and Abusing the F# Dynamic Lookup Operator

Much like C# 4.0 has the ability to do dynamic lookup, F# also has the same capability, although in a different capacity.  The language has support for a dynamic lookup get operator ( ? ) and set operator ( ?<- ), but note that I said support and not actual implementation.  The actual implementation is up to you and how you want to use it. 

 

Matthew Podwysocki’s A Kick in the Monads – Writer Edition

In the past couple of Monads posts, we’ve talked briefly about the State and Reader Monads and their potential uses and misuses.  Before this series completes, I have a few more to cover including the Writer, Continuation and eventually Observable monad.  Today, we’ll get started looking at the Writer Monad and what it can do for us.

 

Ashley Feniello’s Recursion Is the New Iteration

Not all recursive expressions represent recursive behavior. In fact, iteration can be expressed recursively. One trick when considering the process that an expression represents is to think of functions as reducing to values rather than returning them. In a pure functional style (precisely because of referential transparency) you can do analysis by successive substitution.

 

Julien Ortin continues his series on Purely Functional Data Structures with a Real-time double-ended queue, a Skew binary random access list and a Binary random access list

This post describes the F# implementation of the <insert data structure here> from Chris Okasaki’s “Purely functional data structures”.

 

Flying Frog Consultancy Presents - John Conway’s Game of Life in 32 lines of F#

John Conway's Game of Life is a famous example of a simple cellular automaton that produces remarkably diverse results. The game can be implemented in only 32 lines of F# including real-time visualization using Windows Presentation Foundation as follows:

 

Brian McNamara’s An RSS Dashboard in F# (Part 3)

Last time I covered IObservables and we created a useful ObservableSource class.  Today I’ll cover the next technology piece of the app: reading RSS feeds.  I’ll discuss the design considerations regarding how to poll feed for updates and publish feed items as IObservables, and walk through one implementation.

 

Nick Gravelyn’s Pong in F# with XNA Game Studio

A few of my colleagues were discussing F# today and when/where/how it is/isn’t better than C#. I haven’t ever really used F# beyond a very, very brief look at the syntax, so tonight I decided to see what it was all about. As a little project, I decided to make Pong with XNA Game Studio using F# with Visual Studio 2010.

 

Jim Burger’s Maybe F# isn’t for you…

If you aren’t excited about new ways to tackle the concurrency problem, or new approaches to handling generic and mathematical problems, and if the thought of breaking out the shiny new lexer and parser don’t give you a tingle, then maybe F# isn’t actually marketed at you at all.

 

Alex Turner’s Calling F# from COBOL and Back Again (CodeProject)

Running languages on .NET is ultra-powerful. Using managed COBOL (from Micro Focus), it is possible to use F# code to work with COBOL code. Imagine a Cloud based F# map reduce system consuming legacy COBOL - yes, that really is on the horizon.

 

Steffen Forkmann’s New syntactic sugar for “FAKE – F# Make”

The new version 0.27 of “FAKE – F# Make” comes with new syntactic sugar for build targets and build dependencies. Don’t be afraid the old version is still supported – all scripts should still work with the new version.

 

Jared Parsons’s Having fun with events in F#

Recently I ran into a situation where I needed to handle some events in F# in a special way.  In this particular case I wanted to be able to disable and re-enable my handler based on changes in the program.  Essentially the C# equivalent of continually adding and removing the handlers. 

 

Steve Gilham’s “Hello Glade#” from F#

Another bit of spiking, a rather tardy follow up from raw GTK#, starting from the C# example at the Mono Project site, but incorporating the earlier example, so as to build in a clean application exit, for one thing.

 

Luis Diego Fallas’s Using a Webcam with WIA and F#

In this post I'm going to show a small example of taking a picture using a Webcam with Windows Image Adquisition 1.0 . This API seems to have changed in Vista and above, the following code only applies to XP.

 

Flying Frog Consultancy’s WPF Tic-tac-toe demo

The article walks through the design and implementation of a multithreaded program that uses logic programming to create an unbeatable computer opponent and Windows Presentation Foundation to provide a graphical user interface in only 115 lines of elegant F# code!

 

A (Relatively Reasonable) Discussion of F# on Slashdot

OCatenac passes along an interview with Don Syme, chief designer of F#, which is Microsoft Research's offering for functional programming on the .Net platform. Like Scala, which we discussed last fall, F# aims at being an optimal blend of functional and object-oriented languages.

F# Discoveries This Week 01/13/2010


Published to Rick Minerich's Development Wonderland by Richard Minerich January 13, 2010 16:59

Back again this week with a fresh batch of F# Posts, Videos and Events.  I’ve been enjoying Matthew Podwysocki’s “Much Ado About Monads” series quite a lot.  They are well worth checking out for beginner and advanced alike.

 

Events

If you would like to see your event here, send me an email via the link at the top of the page.

Rick Minerich - Charleston SC Technology Users Group on the 27th of January (check out the awesome flier)

Steffen Forkmann - Frankfurt .NET Usergroup on the 21st of January

 

Posts

Don Syme’s Async and Parallel Design Patterns in F#: Parallelizing CPU and I/O Computations

One simple way to write parallel and reactive programs is with F# async expressions. In this and future posts, I will cover some of the basic ways in which you can use F# async programming - roughly speaking, these are design patterns enabled by F# async programming.

 

Don Syme’s F# Interactive Tips and Tricks: Visualizing Data in a Grid

The demos in my F# talks use a number of coding snippets to acquire, generate and display data interactively. Some of these little snippets are not so well known, but they are useful :-)

 

Don Syme’s F# Interactive Tips and Tricks: Formatting Data using AddPrinter, AddPrintTransformer and %A in sprintf/printf/fprintf

Here are some tips and tricks for formatting data in F# Interactive. This is not meant to be a comprehensive guide, just enough to get you started. Please let me know if you need more examples.

 

Matthew Podwysocki’s Much Ado About Monads – Reader Edition

So, our ultimate goal would be instead to have our environment set once and then read from it implicitly.  We still want to keep what we have here in terms of our script, but change the underlying mechanism for how it happens.

 

Anton Schwaighofer’s SkillsMatter.com talk: F# and Units-of-measure for Technical Computing

I will start by giving an introduction to units-of-measure and their implementation in F#. I'll work through smaller and larger code examples that make use of units-of-measure.

 

Nancy Strickland’s MSDev.com Training Session on F#

Visual Studio 2010 includes a new programming language, F#. This session explains and provides a walk-through demonstration of basic programming in F#.

 

Julien Ortin continues his series on Purely Functional Data Structures with a Lazy Pairing Heap, a Real-time Queue and Bottom-up Merge Sort

This post describes the F# implementation of the <insert data structure here> from Chris Okasaki’s “Purely functional data structures”.

 

Mauricio Scheffer’s Translating Haskell to F# and other considerations

BUT, syntactic similarity does not imply that they're semantically the same. There's a fundamental difference from the original code: Haskell is a lazy language, while F#, coming from the ML-family, does eager evaluation.

 

Mark Needham’s F#: Refactoring to pattern matching

I was looking through some of the F# code I've written recently and I realised that I was very much writing C# in F# with respect to the number of if statements I've been using.

 

Mark Needham’s F# attempt at Roy Osherove’s TDD Kata

As I've mentioned in a few of my recent posts I've been having another go at Roy Osherove's TDD Kata but this time in F#.

 

Holoed’s Weak Subscribe to an IObservable Source

A code snippet describing how to subscribe to an event via a weak reference.

 

Erik Schulz’s Resource Pool in F#

I’ve been toying around with F# recently, it’s good to see an example that you can easily compare and contrast with the C# version.

 

Ade Miller’s Gotchas: Common Traps for the F# n00b

I spent a bunch of time over the holidays getting to know F# a bit better. I think I now consider myself to be truly dangerous with it.  A couple of things which repeatedly bit me as I stumbled through learning F# as a n00b.

F# Discoveries This Week 01/05/2010


Published to Rick Minerich's Development Wonderland by Richard Minerich January 05, 2010 21:10

It’s 2010, the year of F#, and the quantity of posts in this last week reflects it.  Not to pick favorites but the work Tomas Petricek has been doing with Accelerator is amazing, be sure to check it out.

Also, I’d like to thank everyone who supported me on the road to becoming a Microsoft MVP.  I couldn’t have done it without you.

 

Tomas Petricek parallelizes Quotations with Accelerator

In this article, we'll look at more sophisticated way of using Accelerator from F#. We'll introduce F# quotations and look at translating 'normal' F# code to use Accelerator.

 

Don Syme Posts updates his F# JAOO tutorial code

I've now updated this tutorial code for the F# Visual Studio 2010 Beta2 release (with matching CTP release for Visual Studio 2008). We've also added some more content and explanatory comments.

 

Matthew Podwysocki investigates the State Monad

In the past, I’ve had a series on Much Ado About Monads where I look at the basic Monads such as Maybe and List, but this time, let’s look at what we can do with the State Monad.

 

Adam Granicz shows off WebSharper at the Hungarian Web Conference

In this talk, I will present our new web development platform, WebSharper(TM), that leverages the power and expressiveness of F# to allow .NET developers to write robust web applications in mere hours.

 

Chance Coble and Ted Neward release DZone Refcardz for F#

This DZone Refcard will lead you through the basic essentials so that you can quickly move on to using this Functional Programming Language for creating some mind-bending code.

 

Talbott Crowell posts his FSUG Parallel Programming Talk

In this video, I discuss some of the advantages of .NET 4 and F# for asynchronous programming plus some of the new analysis tools built into Visual Studio 2010 for visualizing concurrency.

 

Steffen Forkmann creates a ‘FAKE – F# Make’ group on BitBucket and releases version 0.17

Due to its integration in F#, all benets of the .NET Framework and functional programming can be used, including the extensive class library, powerful debuggers and integrated development environments like Visual Studio 2008 or SharpDevelop, which provide syntax highlighting and code completion.

 

Julien Ortin continues his series on Purely Functional Data Structures with a Physicist Queue, a Lazy Binomal Heap and a Bankers Queue

This post describes the F# implementation of the <insert data structure here> from Chris Okasaki’s “Purely functional data structures”.

 

Mathias Brandewinder StackOverflows on Unit Testing with F#

So far, my process with F# has been to write some functions, play with them with the interactive console until I am "reasonably" sure they work, and tweak & combine. This works well on small-scale problems like the Euler Project, but I can't imagine building something large that way.

 

Chas Emerick demonstrates the problem with mutable objects

316 arguments to a method (which I don't think is actually possible in the jvm, but bear with me)? "That's absurd!", you'd say. The problem, of course, is that the 3-arg doSomething actually has far more arguments than its signature implies:

 

A Mysterious Stranger implements a Red-Black Tree

Both 2-4 and Red and Black tress are self balancing trees. They are kind of like cousins, since one could be converted into the other quite easily. Hence all performance analysis that apply to 2-4 trees applies to Red and Black trees.

 

Mark Needham discusses expressing intent with application operators

While trying out Roy Osherove's TDD Kata I realised that perhaps the choice of which of these to use or whether to use them at all depends on what intent we're expressing.

F# Discoveries This Week 12/29/2009


Published to Rick Minerich's Development Wonderland by Richard Minerich December 29, 2009 16:45

It’s been a bit of a light week with the holidays.  Although, for the truly dedicated, that’s just a chance to get some quality time in with with a favorite programming language (or to write a poem about it).

 

Tomas Petricek uses Accelerator in a GPU Game of Life simulation

This article is the second one from a series about using Accelerator from F#. Today, we'll use Accelerator types directly from F# - this is the simplest possible approach and is very similar to the way you'd work with Accelerator in C#.

 

Robert Sundström explores GCD and LCM in F#

I have spent this evening composing some mathematical functions in F#. So far I have just made two for gcd and lcm and one that can identify prime numbers. I want like to share the code with you.

 

Robert Pickering describes his work on FunctionalNHibernate

In the future I’ll be looking at how to broadening what you can do with FunctionalNHibernate ClassMap descriptions and improve data access by integrating Linq like features.

 

Flying Frog solves Rosetta Code’s Data Munging 2 Example

Perhaps the most surprising result is that the F# solutions are extremely concise even when compared with bleeding-edge research languages such as Haskell.

 

Flying Frog plays with Generic Algorithms

The program begins with a random string of letters and spawns a generation of 200 random mutations of the parent string, selects the fittest mutation (by similarity to an "ideal" string) and uses that individual to spawn the next generation. The ideal string used is "METHINKS IT IS LIKE A WEASEL".

 

Julien Ortin uses F# to clean up his temporary internet files

A quick and dirty F# script to clean temporary internet files (including Flash cookies which don’t get deleted by the browsers).

 

Steffen Forkmann observes asynchronous downloads with Rx and F#

This time I will demonstrate how we can use this API and asynchronous workflows to download a couple of websites asynchronous and in parallel.

 

The PFX Team tours the .NET 4 Parallel Programming Samples

On Code Gallery, we have a plethora of samples that highlight aspects of the .NET Framework 4 that help with writing scalable and efficient parallel applications.  This post examines each of those samples, providing an overview of what each provides.

 

Satnam Singh writes a poem about F#

Distracted by Abstraction - A poem about F#

F# for Testing and Analysis at Code Camp 11 New England


Published to Rick Minerich's Development Wonderland by Richard Minerich March 26, 2009 20:18

At this Saturday’s Code Camp I’ll be giving a brand new presentation on using F#.  The goal of this presentation is to have those attending leave with an idea of what F# can help them achieve today as well as instill a desire to know more.  This post contains my presentation materials as well as links to additional information on the topics covered.

(Slide and code links will be updated soon.)

 

Presentation Details

F# for Testing and Analytics will be held in the TBC (Technical Briefing Center) at 10:30am.

New England Code Camp 11 Information
Download Presentation Slides
Download Real World Example Code Sample

I’ve been thinking quite a lot lately on the best way to get developers excited about F#.  By focusing less on the language’s details and more on what the language can help achieve I hope to impress upon those attending why F# is worth the effort.  The preliminary structure of the talk is as follows::

  • Introduction
    • Announcing the New England F# User Group 
  • Why F#?
    • Time Savings
    • Readability
    • Code Exploration
    • Robust Software
    • Visual Analytics
  • F# Testing Toolbox
    • xUnit.NET
    • TestDriven.NET and NCover
    • NaturalSpec
    • FsCheck
    • FsStory
  • A Real World Example
    • Exploring the Problem Space
    • Collect, Analyze, Report
    • Visualizing Data

Presentation Influences
John Hughes’s Paper: Why Functional Programming Matters
John Hughes’s Talk: FP – A Secret Weapon for Software Testing
Matthew Podwysocki’s 7 Part Series: Functional Programming Unit Testing

 

Announcing the New England F# User Group 

I’m proud to announce that we will be holding our first New England F# User Group meeting on Monday April 6th, from 6:30pm to 8:30pm.  It will be held at the aptly named Microsoft NERD center.  I hope to see you there.

Visit the F# User Group Homepage for more information.

 

xUnit.NET

“About a year ago it became clear to myself and Brad Wilson that there were some very clear patterns of success (and failure) with the tools we were using for writing tests. Rather than repeating guidance about "do X" or "don't do Y", it seemed like it was the right time to reconsider the framework itself and see if we could codify some of those rules.”

xUnit.NET Homepage

Learn More about xUnit.NET
Matthew Podwysocki’s The Unit Testing Story in F# Revisited
Jim Burger’s Unit testing in F# with xUnit.NET
Harry Pierson’s Practical F# Parsing: Unit Testing

 

TestDriven.NET and NCover

“TestDriven.NET is a zero friction unit testing add-in for Microsoft Visual Studio .NET. The current release of TestDriven.NET supports multiple unit testing frameworks including NUnit, MbUnit and MS Team System and is fully compatible with all versions of the .NET Framework.”

TestDriven.NET Homepage (Includes a free version of NCover)
NCover Homepage

Learn More about TestDriven.NET and NCover
Matthew Podwysocki’s F# + TestDriven.NET + xUnit = Win 
Matthew Podwysocki’s FP Unit Testing Part 4 – Code Coverage

 

NaturalSpec

“The idea of NaturalSpec is to give domain experts the possibility to express their scenarios directly in compilable Unit Test scenarios by using a Domain-specific language (DSL) for Unit Tests. NaturalSpec is completely written in F# – but you don’t have to learn F# to use it. You don’t even have to learn programming at all.”

NaturalSpec Homepage

Learn More about NaturalSpec
Steffen Forkmann’s “Getting Started” with NaturalSpec
Steffen Forkmann’s Testing QuickSort with NaturalSpec
Steffen Forkmann’s Using NaturalSpec to create a spec for C# projects

 

FsCheck

“FsCheck is a tool for testing .NET programs automatically. The programmer provides a specification of the program, in the form of properties which functions, methods or objects should satisfy, and FsCheck then tests that the properties hold in a large number of randomly generated cases.”

FsCheck Homepage

Learn More about FsCheck
Claudio Cherubino’s Random testing in F# with FsCheck
Matthew Podwysocki’s FP Unit Testing Part 2 – QuickCheck and FsCheck
Kurt Schelfthout’s FsChecking dnAnalytics Part 1, Part 2 and Part 3

 

FsStory

“FsStory is a library for writing executable user stories in F#. FsStory enables the developer to write user story scenarios (in Given/When/Then form) in F# code.”

FsStory Homepage

Learn More about FsStory
Gustaf Nilsson Kotte’s Fluent language in FsStory
Gustaf Nilsson Kotte’s FsStory, executable stories in F#

Discoveries This Week 03/20/2009


Published to Rick Minerich's Development Wonderland by Richard Minerich March 22, 2009 20:09

This week there seems to be quite a bit of video and audio content to share.  We have a dramatic depiction of the benefits of Units of Measure, Luke Hoban on F#’s feature, Ted Neward talks about F# under the hood and finally a discussion on operator type inference.

 

Video Blog – Could F# have saved the Mars Climate Orbiter?

A fantastic example of how static dimensional analysis of scalar values could prevent an entire class of bugs.   In the past, I’ve talked about what a huge fan I am of the Units of Measure package for F#.  I’m glad that others also see how revolutionary units of measure are. 

Would you want to work in a building or live in a house in which the engineers who built it did not keep track of units?  I don’t think anyone would answer yes.  Similarly, we should not entrust our lives or livelihoods to software in which these very same things are not kept track of.

 

Podcast – SER Episode 129 - F# with Luke Hoban

In this podcast Luke Hoban, the F# program manager, discusses about various aspects of F#. 

Some highlights:

  • Mutability comes along with .NET Framework support.
  • Statically Typed means strong guarantees and so robust systems.
  • FP design in the small for concurrency
  • OO design in the large for scalability
  • Explorative programming via interactive window
  • Influenced heavily by Haskell
  • FP as a technique, not a class of languages

 

Video Blog – dnrTV Show #136: Ted Neward Introduces F#

Ted Neward gives an in-depth presentation on both how F# works under the hood and the general benefits that stem from FP in general.  The examples used are simple but Ted covers them in a very exhaustive way.

Beyond the language and concepts therein, he also has a number of insightful comments about teaching people to use F#.  In particular the idea that F# syntax will be easy to teach but functional programming technique will take years really struck home with me. 

 

Blog – Kalani Thielen’s The F# overload-o-phone

In his post Kalani points out a small but significant logical inconsistency in F#’s type inference system.  The issue seems to stem from the way type inference is handled for basic operators.  Instead of working generically, they each have default types.

From his post:

> (+);;
val it : (int -> int -> int)
> 3.2 + 5.4;;
val it : float = 8.6
> let twice x = x + x;;
> twice 9.4;;
stdin(2,5): error FS0001: This expression has type
    float but is here used with type int.

To get around this, he then goes on to build a function which takes an operator and both arguments.  However, this workaround is completely unnecessary.  You need only to annotate the function’s input and it works without issue.

> let twice (x: double) = x + x
val twice : double –> double
> twice 9.4;;
val it : double = 18.8

Now, it’s important to note that this version of the twice function won’t accept an integer.  In fact, it was a conscious design decision to disallow function overloading in F#.  In both F# and C# all kinds of overloading must be qualified by type.  That is, type methods support argument overloading but free floating functions do not.

As a FP Ambassador - F# for Testing and Analysis at Code Camp 11


Published to Rick Minerich's Development Wonderland by Richard Minerich March 19, 2009 16:00

Over the last six months I’ve given variations on the same F# presentation on six separate occasions.  Each time I’ve gotten a similar response: enthusiasm from a small percentage of the audience and glazed-over stares from the majority.  In retrospect it seems obvious that I’ve been missing one of the major tenets of making great presentations, know thy audience.  It’s time for a new approach.

 

Information Overload

When thinking about how to get people excited about F# I immediately jumped to the learning format that I found the most exciting.  There was no time in my life when I was as overwhelmed by information like I was working on my Computer Science degree at UMass Amherst and I loved every minute of it.  When I started out, it seemed that using a university lecture as a model was the best possible format for sharing this kind of information.

I’ve since come to realize that this style of soaking the audience with “a fire hose of information” is a poor format for Code Camps.  While using this technique, I could see people turning off one by one as they became overloaded with information.  This is not in the spirit of code camp which aims to be a much more laid back kind of experience. 

 

As a FP Ambassador

Let’s invert perspectives and think about what an audience member would want.  When a person comes to a Code Camp presentation, it’s likely to be one of their first times being exposed to the topic being presented.  They don’t want to be taught as if they were in a classroom.  Instead, they want to be exposed to new and exciting information.  If their interest is piqued, they will seek details later.

So, instead of focusing on the details of F#, this new presentation will be built around the goal of instilling five key ideas to the audience:

It must be understood that almost every Code Camp attendee will have had little or no exposure to functional programming.  To many attendees, to be presenting on F# is to be an ambassador from the strange and nebulous functional programming world.  Instead of building walls of information, the goal should be to instead focus on connecting with the audience on the benefits of functional programming.

 

Planned Talk Structure

  • Depending on an Audience Poll, Broad Concepts
  • Testing with F#
    • nUnit Examples (as a baseline)
    • xUnit Examples
    • FsStory Examples
  • Analysis with F# (A Real Example From Atalasoft)
    • Using The F# Interactive Window To Build Tests
    • Data Collection
    • Visualizing Data
  • Conclusion
    • Why F#?

More details will follow soon.

Discoveries This Week 03/13/2009


Published to Rick Minerich's Development Wonderland by Richard Minerich March 14, 2009 21:14

This week we have ActionScript byte code manipulation, COM interop in F#, a quick look at the option type, and finally, a very elegant cross product implementation.

Blog – Luis Diego Fallas’s Manipulating AVM2 byte code with F#

This article focuses on using AbcExplorationLib to parse AVM2 ActionScript byte code.   AbcExplorationLib is still rather new and does not yet have complete support for all AVM2 instructions.  However, it may eventually be useful for static analysis or, in the best possible case, flash generation from within .NET languages. 

 

Article – Richard Marsden’s Functional Programming with MapPoint and F# (Part One)

In this post Richard initially walks through the steps involved in getting COM Interop in F# via both early and late binding.  He then goes on to programmatically load up a new MapPoint instance and instantiate a pushpin on it.  Once the painful COM stuff is out of the way it seems F# could make a rather nice scripting language for Microsoft apps such as this.

We’ve been told that C# 4.0 will offer COM interoperability that is significant less painful due to it’s new named arguments, dynamic typing and language binding layers.  After reading this article, I can’t help but wonder how much of this (if any) will be available in F#.  In the CTP release both early and late binding are rather painful.


Stack Overflow – How does the option type work in F#?

It’s a rather simple question, but I do like how the community came out to help answer it.  Although, I do think it’s very debatable whether null or -1 make for a better answer to the question “how long is this null string?”.

Generally, I’m opposed to hiding information inside of a type meant to hold something else, especially if it’s a scalar value.  Were it not for the overhead involved, in C# I would think the best solution would be to throw an exception.  Inside F#, at least with option types you know you are handling an exceptional case and not just an empty variable.  Yet another great benefit of immutability.

 

Stack Overflow – F# – Cross Product of Two Lists

I wanted to include this as Tomas Petricek’s solution was extremely elegant.