Slick Use Case For Active Patterns

So I love it when a very natural use case arises for a feature that I want to practice.  I’ve been trying to better my understanding of active patterns lately and today I found a great use for them.

I’m fetching json data from a REST endpoint.  Of course I get back a string.  And the string contains some very specific text when there’s a problem processing the request on the server side.  So I ended up doing something like this:


let errResult = "Error creating user"

let (|ContainsErrString|) (stringToTest:String) = stringToTest.Contains(errResult)

//And further down in the code:

let res = sr.ReadToEnd()

let u1 =
 match res with
 | ContainsErrString true -> None
 | _ -> Some(JsonConvert.DeserializeObject<user>(res))

Simplifies the code dramatically and hides detail that the match doesn’t need to know about.  Terrific use case for an active pattern.

F# Tip Of The Week (14 October 2013)

It is possible to declare a list or an array without the separating semicolons by declaring each element on a separate line.  Like this:

let favoriteBreeds = [
    "Antwerp"
    "Carneaux"
    "Swiss Mondaine"
]

//Array

let favoriteBreedsArray = [|
    "Antwerp"
    "Carneaux"
    "Swiss Mondaine"
|]

Note: for reasons I confess are unclear to me, the first member of the list/array must be on the next line from the opening symbol of the collection. Well, to be precise (this is software development after all) this is true of arrays–the same is not true of lists. But since putting the first element of the array on the next line works in both cases, it’s simplest just to do it this way.

EDIT: Per Dave Thomas, you can put the first element of the collection on the same line as the opening symbol; you just need to insure that you align all of the other elements, DIRECTLY beneath the first element, as in this code gist which Dave put up.

Personally I consider it’s easier to simply stick to the convention of always putting the first element on the next line so you don’t have to worry that much about the alignment but this does work.

 

Functional Programming Makes Simple Easy

I do love the fact that F# (and functional programming in general) gives a developer the tools to make it easy to build simple code.
I was hacking together a function to convert a DateTime to a Unix Time Stamp (for using with the Meetup Restful API).  This was my initial pass at it:
    let unixTimeStamps startDate endDate=
        let startOfEpoch = new DateTime(1970,1,1)
        let startTS = uint64 (startDate - startOfEpoch).TotalMilliseconds
        let endTS = uint64 (endDate - startOfEpoch).TotalMilliseconds
        (startTS, endTS)
(BTW that may not be the exact working code but it should give the idea.)
Then I thought to myself–why should I return a tuple?  If I simplify the function to simply convert a DateTime to a UTS, I can just call it twice.  So I got this:
    let unixTimeStamp d =
        let startOfEpoch = new DateTime(1970,1,1)
        uint64 (d - startOfEpoch).TotalMilliseconds
Simpler but still not as simple as I could make it.  I was bothered by the fact that I had to truncate the decimal part of the returned timespan.  I had to truncate it because Meetup’s API balks at a time span with a fraction on the end of it.  So I modified the function one more time to make it both simpler and more generic:
    let unixTimeStamp d =
        let startOfEpoch = new DateTime(1970,1,1)
        (d - startOfEpoch).TotalMilliseconds
And I added a little function composition to handle Meetup’s little quirk:
    let fixUnixTimeStampForMeetup = unixTimeStamp >> uint64
At any rate, this is part of the reason I’ve got such a crush on FP and F#.  It does make it easy to build simple, reusable but still generic code.

F# Tip of the Week (26 August 2013)

It’s possible to use function composition and modify the type of value returned.  Consider the following equation:

1/4x2

I might encode the function to calculate this like so:


let square x = x * x

//Want this to be a float because if this is an int division

// it will always round to 0 if x is greater than 1.

let recip x = 1.0/x

let myFunc =  fun x -> 4* (square x) >> recip

This function composition will not work because I need to pass a float to recip. But I can make it work by doing this:


let square x = x * x

let recip x = 1.0/x

let myFunc = fun x -> 4* (square x) >> float >> recip

 

There’s a great deal more information on conversion functions in F# here.

F# Tip Of The Week (Week of August 19, 2013)

Even though tuples, records and discriminated unions are reference types, they all have the built-in equality properties you would expect in a value type.  For example:


> let a = (1,'a');;

val a : int * char = (1, 'a')

> let b = (1,'a');;

val b : int * char = (1, 'a')

> a = b;;

val it : bool = true

That is, you get the equality behavior you would expect rather than the usual equality behavior associated with reference types.  Here’s an example of records and the built-in equality checking:


> type rec1 = {

a:int

b:string

};;

type rec1 =

{a: int;

b: string;}

> let a = {a=1;b="one"};;

val a : rec1 = {a = 1;

b = "one";}

> let b = {a=1;b="one"};;

val b : rec1 = {a = 1;

b = "one";}

> a = b;;

val it : bool = true

F# Tip Of The Week (Week of August 12, 2013)

The F# developer can use pattern matching syntax pretty much anywhere in F#.  For example, consider the following list:


let l = [1..25]

If I want to get the last element of the list, I can do this with a little trivial pattern match:


let lastElem::_ = l |> List.rev;;

stdin(7,5): warning FS0025: Incomplete pattern matches on this expression. For example, the value '[]' may indicate a case not covered by the pattern(s).

val lastElem : int = 25

In this case, you can safely ignore the warning.

You can also pull one of the elements from a tuple very easily with this pattern match:


let name,_ = (“Onorio”,”11W”);;

val name : string = "Onorio"

The underscore character in both of these pattern matches functions as a wildcard.  In both cases it signifies a value that we don’t care about.

Getting The Band Back Together

So back in 2011 I was trying to get an F# user group going here in Detroit.  As is so often the case with user groups, most of the responsibility for setting things up and arranging things was falling on one person–me.  In fairness, the folks at Epitec did their best to help; they provided us a place to meet and they provided food.  Still I was the one always doing the presentations and, as anyone who’s ever run a user group knows, that burns a person out in short order.

Still I really wanted people to know the F# story; I think it’s very compelling.  Fast forward to 2012 when I joined John Fair at Quicken Loans.  John is another F#anatic (to coin an unnecessary neologism). John and I have both been running a weekly F# learning session for quite some time.  So yesterday I felt it’s time to apply some of what I’ve learned since 2011 and give another try to running an F# user group here in Detroit.  John has graciously agreed to help and I know that means I won’t be stuck doing all the heavy lifting.

We’re meeting on August 22; location is still to be determined as is the topic of the first meeting.  But either way, I am excited to once again be able to start sharing the F# goodness.  And there is a lot of goodness there.

http://www.meetup.com/Detroit-F-Meetup/

CodeStock 2012

First of all, kudos to Michael Neel and everyone that put on CodeStock.  This was my first time attending CodeStock and to see such a well-run conference is always a pleasure. I know from experience that there’s a lot of work that goes in to making things run that smoothly.

I got to attend a few very interesting sessions.  Mike Falanga’s session on using F# and MongoDB for analysis of large datasets was very interesting.  Daniel Mohl’s session on F# and Web Development was also good—and it was really nice to meet Daniel in person and get a chance to gab with him a bit.  There were a few folks from the Nashville area at the conference and they must have some major-league brain power out that way.

Also Rob Gillen’s talk on how buffer overflow attacks work was both fascinating and a bit scary. I can just imagine how many unpatched vulnerabilities there are running around in all the publicly deployed sites I regularly depend on.

Finally, here’s the slide deck for my F# Shell Scripting Talk.  I’ll edit this post later to share sample code.  I’ve posted the slide deck as a PDF file to maximize the number of people that can see it.

Note: Thanks to Dennis for pointing out to me that I got the name of the presenter for the buffer overflow attack talk incorrect. 

Why The Defaults Matter

I often think of why I feel that it’s important to have a functional language—not just write code that’s pseudo-functional in an imperative language.  As I think this through, I wanted to record some of my ideas on the subject.

Even the best developers I’ve known are almost always inclined to take the defaults.  I mean if the default string type is ASCII then you’re very unlikely to see Unicode strings in the app unless someone specifies that this is needed.  This is not laziness; it’s simply that these developers have other issues to concentrate upon.

Why is this important?  Simply this: I’ve come to realize that default mutability is an accidental complexity–in the sense that Fred Brooks used that term in his “No Silver Bullet” essay.  Don’t misunderstand what I’m saying–mutability is necessary and appropriate.  But having all values in software mutable by default is an invitation to lots of unexpected side effects.  And this is why I really believe that functional languages will continue to gain in use.  Functional languages are immutable by default.  Impure functional languages (OCaml, F#, Clojure, and Scala among others) do allow a programmer to specify mutable quantities where it’s appropriate due to performance considerations but they default to quantities being immutable–and that’s why they’re important.  If things default to being immutable, developers will learn to work with immutable quantities and become accustomed to them in the same way they’re now accustomed to thinking in Objects.  People seem to forget that 30 years ago, OO was as much an academic discipline as Functional is now.

Every developer knows they should mark quantities as constant (or final or readonly or whichever keyword expresses immutability) but most do this only as an afterthought and they do it incompletely.  Default immutability could eliminate a whole class of side-effect errors and therefore reduce errors in our code by a large fraction of all errors present. The issue is not the question of does “const correctness” (for lack of a better way of phrasing it) make software less error-prone; the issue is getting developers who are always under impossible deadlines to use constants by default.  Languages that default to constant, immutable quantities are a large step in that direction.  This is why functional programming is important and this is why you’re going to inevitably see more and more developers gravitating toward these functional languages.