• The Road to Functional Programming in F# – From Imperative to Computation Expressions

    In F# there are a lot of options when it comes to choosing the style in which you will perform a computation.  So, for our last meeting of the the NYC F# User Group I decided to try and build a general understanding of how the different styles are related to each other through trying them and discussing our results. Come along with us and explore five of different styles of programming in F#.

    For our example I chose Project Euler #1 as it’s simple and wouldn’t get in the way of contrasting the different computation styles.

    Find the sum of all the multiples of 3 or 5 below 1000.

    As there are a lot of people out there that are new to F#, let’s start with an imperative approach.  That way we can all feel comfortable and see how the other styles relate.

    let pe1_while limit =
        let mutable acc = 0
        let mutable x = 0
        while x < limit do
            if x % 5 = 0 || x % 3 = 0 then acc <- acc + x
            x <- x + 1
        acc
    
    pe1_while 1000
    

    Next, let’s move on to doing the same thing recursively.  This transition is the first step on the long road of functional programming and it’s important that new users see how the two basic patterns map to each other.  For this reason, I kept everything but the style of computation the same.

    let pe1_rec limit =
        let rec inner_pe1 x acc =
            if x < limit then
                if x % 5 = 0 || x % 3 = 0 then
                    inner_pe1 (x + 1) (x + acc)
                else
                    inner_pe1 (x + 1) acc
            else acc
        inner_pe1 0 0
    

    As you can see, the combination of the first if and the recursive calls correspond to the while statement.  The predicate remains the same.  The biggest conceptual hurdle for new users here is that for both predicates a course of action must be explicitly specified in both the success and failure case.

    Another important idea here is that when doing recursion you don’t want to leave anything left undone on the stack. If you do, the compiler can’t do tail call optimization. Without tail call optimization each recursive call will create an additional stack frame. This slows things down and can even crash your program by overflowing the stack if the recursion goes too deep. As long as you don’t leave anything left undone your recursive function will run just as fast as a while loop.

    I constructed this example with the thought that it would be best to avoid having to explain too many new constructs at once.  However, while discussing this solution one new user remarked that this looked like spaghetti code.  In response to this Paul, one of our more advanced users, whipped up a much nicer solution utilizing pattern matching.

    let pe1_rec2 limit =
        let rec inner_pe1 acc = function
            | 1                     -> acc
            | i when (i % 3 = 0)
                  || (i % 5 = 0)    -> inner_pe1 (acc + i) (i - 1)
            | i                     -> inner_pe1 acc       (i - 1)
        inner_pe1 0 (limit - 1) 
    

    Now that’s some pretty code!  While it may have some intermediate concepts, the recursion looks just beautiful when structured with a pattern match.

    Still, to most I think this hardly seems worth giving up mutation for.  This is why we should move on to pipelines and comprehensions next.

    let pe1_seq limit =
        seq { 0 .. limit - 1 }
        |> Seq.filter (fun x -> x % 5 = 0 || x % 3 = 0)
        |> Seq.sum
    

    While bound to perform somewhat slower due to the use of sequences, it’s hard to imagine a more conceptually elegant solution to this problem. In comparison to the imperative version, the sequence comprehension takes on the role of both the while loop and the incrementor in generating the sequence values, the filter acts as the predicate and the sum as the accumulator.

    The final two examples I’ll show you were more for fun and to provide a challenge to the intermediate and experienced users.  Conquering folding and unfolding were some of the biggest hurdles I faced when learning functional programming.  Just getting comfortable with how accumulators work takes some time for everyone.  For practice let’s use fold in our pipeline instead of filter and sum.

    let pe1_fold limit =
        Seq.init limit id
        |> Seq.fold (fun acc x -> if x % 5 = 0 || x % 3 = 0
                                  then acc + x
                                  else acc) 0
    

    Here we took a somewhat different route when generating sequence values by using the Seq.init function.  As I discussed in my Ted Neward’s Folding Challenge post, the contents of the folding function can be directly mapped to the imperative and recursive solutions.  Just as in the first two examples the adding is done explicitly right along with the application of the predicate.   The biggest conceptual difference in this example is that the accumulator is passed as the return value of each call to fold instead of being kept in a mutable variable as in the imperative version or explicitly passed forward as in the recursive.

    Finally, as a challenge to the most experienced users let’s see if we can do this with a computation expression.

    type Euler1Builder() =
        member b.Combine(x, y) = x + y
        member b.Zero() = 0
        member b.Yield(x) = if x % 5 = 0 || x % 3 = 0 then x else 0
        member b.For(vals, f) =
            vals |> Seq.fold (fun s n -> b.Combine(s, f n)) (b.Zero()) 
    
    let eb = new Euler1Builder()
    
    let pe1_eb limit = eb { for x = 0 to limit - 1 do yield x }
    

    This first attempt is what I showed off at our user group meeting.  It’s embarrassingly ugly and ends up just being a convoluted way to generate a sequence and fold over the values.  Since the meeting I’ve fiddled with it a bit and have come up with a solution I like much more.

    type Euler1Builder2() =
        member b.Yield(x) = if x % 5 = 0 || x % 3 = 0 then x else 0
        member b.For(generated, f) = generated |> Seq.map (fun x -> f x)
        member b.Run(filtered: int seq) = filtered |> Seq.sum 
    
    let eb2 = new Euler1Builder2()
    
    let pe1_eb2 limit = eb2 { for x = 0 to limit - 1 do yield x }
    

    Instead of being like the fold example, this is much more like pipeline.  The only downside here is that the computation expression attempts to be as generic as possible and so we need a type annotation to make the example compile.  Overall, I think it ended up looking quite nice.  It’s also not nearly as complex as you might think.

    Let me explain how each of the members of the computation expression fit together to make this work.  The builder’s For method allows us to use a for loop within our expression.  The values generated by that for loop are provided to the For method in the form of a sequence.  When For is called, it is passed that sequence along with a function which does whatever is scoped inside of our expression’s for loop.  In this case, that function is the builder’s Yield method because we are yielding each value.  Finally, the entire computation is preformed within the context of the Run method, which allows the input and output of the expression to be manipulated.  So, within our example we generate our values with For, filter them in Yield and then finally sum them in Run.

    I hope you’ve enjoyed our journey through the different styles of computation in F#. The only style I think I didn’t cover here is continuation passing, which is more of a hack to get around the limits of recursion and linked lists anyway.  If you do think of something I missed, want to discuss something related or just feel like being friendly I hope you’ll leave a comment.

  • F# Code and Slides to Share

    As I mentioned in my most recent edition of F# Discoveries This Week, it’s Code Camp season and it would be great to see more F# users out there sharing the love.  To help out, I’ve provided the slides from my previous talks in one place under the Creative Commons Attribution license.  I even left all of my slide notes intact.  Do anything you want with them, but please do it in the spirit of spreading F#.

    Of course, this applies only to my own slides and code.  Everything made by someone else maintains its existing license.  Duh.

    As evidenced by this picture of Don Syme, speaking on F# is guaranteed to make you look at least 200% more awesome

    F# and You!

    This was my go-to intro to F# talk for almost two years.  It’s a whirlwind tour through F# with an emphasis on conveying why F# is good over how to use it or how it works.  I’ve given variations of this talk over 10 times, and it’s always a crowd pleaser.

    Functional Language Paradigms in F#

    I gave this talk at the NYC ALT.NET Group shortly before moving to NYC.  It may just be my most well received talk of all time.  If you use this, you’ll need to switch up the questions so people can’t just look up the answers online beforehand.

    F# For Testing and Analysis

    This talk is an overview of some of the tools available for F# and how to use them.  It’s one of my favorite talks for intermediate F# users.  FsCheck always blows the minds of those who are engineering-minded.

    A Lap Around the F# Ecosystem

    While similar to F# for Testing and Analysis, this talk focuses on some great tools not involved in testing.  For example, I give FAKE some love.

    F# 2.0 – A Day at the Beach

    This is the content for my CUFP tutorial.  Giving this talk involved a ton of answering questions and walking around helping directly.  The code is a bit dated, I have a much more recent Silverlight version you can use instead.

    F# in the Lab and the Classroom

    This was my first attempt at spreading F# in academia and I think it went much better than I expected.  My favorite part is the comparison of a pseudo decision tree with F#’s match statement.

    Love the Lambda

    This talk is a bit of an unfinished project.  The basic idea is that F# allows you to implement features that would requite compiler changes in languages like C# and VB.NET.  I’ve given it only once with mixed results, but I think it has a lot of potential.

    I’ve given a few others but they’ve either been composites of what I posted here or are so old that none of the samples would work now.  I hope that by providing these here I’ve inspired at least one other person to get out there and share the F# love.

    I’d love to hear about how you used these slides or answer any questions you might have.  The best way to get in touch is with twitter.

  • I got 99 problems but dynamic ain’t one

    If you got runtime errors I feel bad for you son
    I got 99 problems but dynamic ain’t one

    I got the cube patrol on the code patrol
    Foes that wanna try and keep my source out of control
    Ruby writers that say he’s “Science Strict Not-Bold”
    I’m from university stupid what type of facts are those

    If you grew up with segfaults in your joes
    You’d celebrate the minute you was havin’ stable codes
    I’m like avoid Python it can’t handle my whole payload
    If you don’t trust my types you can take my tests off hold

    Got beef with podcasts if Iron’s on they show
    When those brakepoints hit they don’t know what’s missed
    Soft’ mags try an’ ignore my syntax
    So readers can buy more tools from ads…

    I don’t know how you be writin’ that
    without understanding the power that type systems have
    I’m from calls to lambdas dude, I ain’t dumb
    I got 99 problems but dynamic ain’t one
    Hit me

    99 problems but dynamic ain’t one
    If you got runtime errors I feel bad for you son
    I got 99 problems but dynamic ain’t one
    Hit me

  • An F# Ant Colony Simulation in Silverlight 4.0 with Dynamic AI Loading

    I’ve been enviously watching Phillip Trelford publish excellent F# games all week and tonight I just couldn’t stand it anymore.  I stayed in, rolled up my sleeves and ported the very same ant colony simulation I used in my CUFP workshop to Silverlight 4.0.

    <Silverlight Demo was Here, but unfortunately no longer works>

    Wow, just look at those little guys go at it.  Silverlight sure is pretty!

    As you might have noticed by the big white “Click To Load Custom AI” message, you can also compile your own AI and battle it out with what I’ve included here.  To make things easy I’ve provided a ready to go solution.  Simply load it up, compile it and select the compiled DLL.

    Once you’ve loaded your AI the game will immediately start.  Best of luck to you against my little monsters, so far they’ve been undefeated.  If you happen to come up with an ant-dominating example I hope you’ll post it here in the comments.  There were some really creative ideas in the CUFP workshop and I’d love to see what could be done with more than just four hours.

    If your interested in the gory details of the simulation itself, I’ve put up a github repository with the entirety of the code.  And just in case you’re wondering, I’m still planning on running that contest.  Expect a ton of cool new AI features and a big focus on combat.

    Cheers!

    Update:  I’ve mucked with a few things.  Mainly, it will be a bit nicer when handling AI exceptions now.  While I was at it I tweaked some of the game world parameters and so you’ll need to re-download the example solution if you already have it.

  • In Retrospect: The F# in Education Workshop

    I was taking the elevator down after getting settled in my hotel room and as the doors opened I was awestruck by the sight of Don Syme sitting on a couch, typing away on his laptop. With a bit of trepidation I walked up to him and introduced myself.  It was immediately obvious that he was both a very friendly fellow and very excited about something in particular.

    Don turned his laptop to me and said “look at this”. It was a blog post detailing the release of F# under the Apache 2.0 license. Needless to say, my mind was blown. I was dumbstruck.

    Don Syme announcing to the world that F# would forever be under the Apache 2.0 license. (Photo courtesy of Migel de Icaza)

    We then proceeded to dinner in the hotel restaurant. Miguel de Icaza was there, and if you know Miguel you know he’s the life of the party. He became even more animated when told about F# becoming open source and pledged to get the source integrated into Mono as soon as possible.

    Later that night the Hotel turned into some kind of giant dance party and fashion show.  Thinking of the day ahead we all returned to our rooms.  I did sneak back down later though to grab a celebratory book-publishing nightcap with Ted Neward.  It’s old hat for him, but I’m still reeling from it.

    Announcing Professional F# 2.0! (Click for Video)

    To be honest, I was a bit intimidated by the idea of speaking to a room full of PhDs. Because of this, I put far more thought and practice into this 30-minute presentation than any of the much longer talks I had given before. Having my material down pat, I was able to turn that anxiety into gusto with what I feel was great success.

    While presenting I noticed that the entire room was laughing at my jokes at first but by the end most seemed rather serious.  I took this to mean that many were offended by my critique of current teaching techniques. Had I been too heavy handed with my language?

    Afterward my fears were allayed by the enthusiasm of those who came and spoke with me. Later, a swath of positive reviews confirmed that, while I may have been skirting the edge, I hadn’t gone too far.  Even so, I think I’ll try to be a bit softer in my approach in the future.  As they say, you attract more flies with honey than with vinegar.

    Judith Bishop
    Queen of Microsoft Research
    Miguel de Icaza
    Lord of all things Mono
    Tomas Petricek
    F# Jedi
    Joe Pamer
    Tamer of F# Compiler Lions

    Photos Courtesy of Microsoft Research

    That night I had dinner and drinks with some of the most brilliant people. Conversation ranged from type systems to the future of F# and Mono. I ended up staying up quite late talking with Tomas about his future plans. It looks as though he has a ton of great stuff for the F# community right on the horizon.

    Howard Mansell
    The F# Prophet of Credit Suisse
    Richard Minerich
    Who invited that guy anyway?

    Photos Courtesy of Microsoft Research

    The next day Howard and I took the train back to New York and discussed our plans for NYC-wide F# domination. Howard is almost single-handedly responsible for Credit Suisse’s rise as one of the biggest F# using companies. They now number over 100 F# users strong and continue to grow. Combined, we might just be unstoppable.

    All-in-all I’d say that the event was a great success both personally and for F#. In a couple of years we’ll see some of the first big batches of graduates educated in statically typed functional programming. At that point, those the imperative object oriented camp will need to start playing catch-up.

  • An F# Whirlwind

    Just under two weeks ago I was packing up my things at Atalasoft and enjoying my last Friday Beer:30 with coworkers and friends.

    My last Beer-30 at Atalasoft

    A lot has changed in these past two weeks. I’ve moved into my Hoboken apartment and (partially) assembled a whole set of IKEA furniture, I’ve gotten started as the first employee at a brand new company called Bayard Rock, and I’ve seen quite a few exciting things happen in my own little F# world.

    First, I’ve managed to get a new site up for my F# Discoveries This Week blog series. It’s called F# Central and I hope to do big things with it far beyond the scope of my weekly blog post. Stay tuned.

    Second, after a year of blood, sweat and tears Professional F# 2.0 has been released.  I wrote the entirety of Part 3 and worked hard to convey every moment of functional programming epiphany that I experienced while learning F#.  I hope you’ll pick up a copy and let me know what you think.

    Third, this Friday I’ll have the great honor of speaking alongside giants such as Don SymeTomas PetricekJudith BishopJoe Pamer, and Howard Mansell at the F# in Education workshop. In my talk entitled F# in the classroom and the lab, I’ll be drawing on my own past experiences in order to paint a picture of how F# can be used to improve all aspects of academic life.  Even if you can’t make it in person be sure to watch it via the internet simulcast.

    Finally, with the help of my good friends Rachel Appel and Howard Mansell I’ve got everything in place for the first meeting of the New York F# User Group.  I’m getting the feeling that the NYC F# community is about to explode and I hope you’ll be part of it.  Come join us if you’re in the area and help spread the word if you aren’t.

  • A CUFP Tutorial, F# Day at the … Oh God, Ants!

    Everyone was ready for a nice relaxing day at the beach when they showed up for my CUFP tutorial…

    A Day at the Beach, Interrupted

    So, after realizing how boring it would be teach thirty flavors of factorial to experienced functional programmers for four hours, I thought I’d spice things up a bit. AI is always fun and I do love ants, so why not a contest where attendees would write Ant AI to gather food? For a bit of additional motivation to get everyone over the post-lunch slump, I decided to give away one of my Visual Studio 2010 Ultimate Edition MSDN subscriptions as a prize.

    Just look at those little guys go.

    In thinking about how I would run this contest, it occurred to me that the AI better be pretty frickin easy to write. Four hours is not a lot of time to both learn a language and write something cool in it. Below is a modified (to fit nicely on my blog) version of the Ant AI for the red colony above, which is what I provided as a baseline sample for participants to test against.

    match me with
    | HasFood
    | HasMaxFood ->
        match locations with
        | HasUnownedFood cells
            when not (here.HasPheromone me.Color) ->
                DropPheromone (here, 100)
        | NearHome homeCells ->
            match homeCells with
            | CanDrop dropCells -> DropFood dropCells.Head
            | CantDrop -> Move homeCells.Head
        | AwayFromHome allCells ->
            if not homeDirectionCell.ContainsAnt
            then Move homeDirectionCell
            else match randomEmptyLocation locations with
                 | Some location -> Move location
                 | None -> Nothing
    | HasNoFood ->
        match locations with
        | HasUnownedFood foodCells ->
            TakeFood (maxFood foodCells)
        | SmellsPheromones pheroCells ->
            Move (maxPhero pheroCells)
        | _ -> match randomEmptyLocation locations with
               | Some location -> Move location
               | None -> Nothing
    

    We all had a great time. Most didn’t even take the given breaks other than to run out quickly to the bathroom or grab a coffee. When time finally ran out I was proud to have three finalists who stayed and watched their ants battle it out, one of whom completed the entire project in Mono/Linux (Mono on MacOS, not so much).

    The three finalists: Frank Levine, Phil Clayton and Paul Greene.

    Paul’s rather clever ants did what they could to block the opponent’s nest while gathering food. Phil, despite having some delays getting going due to my lack of experience with mono, made an excellent showing. However, in the end little could be done to stem the tide of Frank Levine’s pheromone gradient following ants.

    As runner up, Phil will be getting a fresh copy of Professional F# 2.0 as soon as they hit my doorstop. Frank won the day and took home his very own MSDN Ultimate subscription.

    Frank wins the day.

    All of the tutorial feedback was great. To my surprise, those who had trouble getting my code running on their Macs seem to have had a fun time. For days afterward I received emails from people who kept working on the problem even after they went home from the conference!

    Currently I’m working on putting together a larger version of this contest online. I hope to extend the model used in this to include combat, spawning new ants and maybe even decaying dead ants. Send me a message on twitter if you’re interested in helping to beta test the engine.

    I want to thank all of the attendees for coming, having fun, and putting up with the various cross platform issues. I also want to thank Martin Logan and Anil Madhavapeddy for helping to make this session happen. Finally, I want to thank Paul Greene for reporting a behavior related bug he found afterward through experimentation. It’s fixed now in my local source, but not in the files you can sneakily grab from the Mono bug report above ;).

    I hope all of you CUFP tutorialists will join me in the next iteration of this contest. It’s sure to be a blast.

  • Learning F# for Fabulous Prizes

    Nearly a month ago I visited the NYC ALT.NET User Group in Manhattan.  Having been told by Steve Bohlen that I was up against a particularly sharp audience, I decided to do something much different than I had in any of my previous talks. Spread throughout my slides were questions. Those who answered correctly first were given F# stickers that they were later able to turn into various prizes.

    I found that the anticipation caused by not knowing when the next question might be asked kept attendees on their toes. Energy ran high throughout the session, higher than I’ve ever seen before. That said, never before have I had the pleasure of having such an intelligent and attentive audience.

    Along these lines, I’m planning on running a contest at my upcoming CUFP F# tutorial. Grand prize will be a MSDN Subscription with Visual Studio 2010 Ultimate. I know many in the audience will be running Linux or OSX, but it’s just about the best thing I have on hand to give away and I’m fairly certain that it comes along with Windows 7 so you can run it in a VM.

    Many thanks to Alex Hung who has provided high quality video of my NYC ALT.NET talk.

    <Sorry, the videos for “Functional Language Paradigms with F#” seem to no longer be available on vimeo>

    Note: On the Async question: I suggest using function composition and sequences for discrete element transforms. I don’t know why it didn’t occur to me to mention it.

    Note: For the DSL question: You do get intellisense within a module. For your DSL you can just put your grammar into a module and then blamo, intellisense.
    Errata: I was wrong about the compiler sources. It turns out the compiler source is available in the CTP. Vladimir Matveev has written a great post on how to build it.

  • The Language Matters on the Software Engineering Productivity Podcast

    Actually, I used my phone.

    In this episode, Richard Minerich tells why the language developers use can have a huge impact on their productivity. New high level languages, like F# (one of Richard’s favourite languages), free engineers from much of the traditional drudgery leading to faster development cycles and better quality.”

    I recently had the pleasure of being a guest on Michael Surkan’s Software Engineering Productivity podcast.  The topic: why language choice matters in software engineering.  Michael contacted me to join him on his show after many pages of heated debate on a topic I started in his Linked-in group of the same name.  It seems many still feel that language choice has little impact as long as it meets the basic project requirements.  I disagree.

    Listening to it afterward, I think I did quite a good job of getting most of the many ‘whys’ across.  Not bad for 20 minutes.

  • In Retrospect: TechEd 2010 North America

    Celebrity photo op with Sara Ford

    This year I was invited by Microsoft to attend TechEd 2010 North America in New Orleans.  Largely, I was to be found at the Visual Studio languages booth answering questions about F#.  It was exhilarating to hear so many developers come up and talk about how they were planning to use F# to tackle what they previously thought insurmountable.  Most often I heard engineers tell me about how they wanted to paralellize complex computations but didn’t want to sacrifice the readability of their models.  Although, a great many were also excited just to dig into some new language features and to try and understand programming in a new way.

    One of the most exciting things about the trip was that Amanda Laucher and Ed Hickey helped me to put together an on-site meeting for the New England F# User Group.   Steffen Forkmann spoke on his F# projects from Germany to two audiences: one at our usual location in at the Microsoft Nerd Center in Cambridge, Massachusetts and another at TechEd NA 2010 in New Orleans.  Thanks to Talbott, who was facilitating the Cambridge meeting along with Michaela video of the talk is now available online.

    I spent my off time hunting down smart people and forcing them to hang out.  Thankfully, most didn’t seem to mind.  The Visual Studio languages guys were friendly as always.  Of the few I didn’t meet at the MVP summit, it was most fantastic to finally meet Amanda Laucher in person.  When she’s around things just seem to magically come together.  I also had some awesome times with Alan Stevens, a man even more rad in person than in the stories they tell about him.

    That Friday I hopped on a plane euphoric and exhausted, and headed to Singularity Summit 2010 for a slightly more intellectual, but much more subdued time.