_______1 |> F# – Getting Started, Thinking Functionally (Notes)

Recently I took the plunge into writing F# on OS-X and Linux (Ubuntu specifically). This is the first of a new series I’m starting (along with my other ongoing series on JavaScript workflow and practices). In this article particularly I’m just going to provide an overview and notes of key paradigms in functional programming. Most of these notes are derived from a great series called “Thinking Functionally“.

#1 Thinking Functionally: Introduction

This is the article that kicks off the series. The emphasis is focused around realizing that a different way of thinking needs applied when using a functional language. The difference between functional thinking and imperative. The key topics of the series includes:

  • Mathematical Functions
  • Functions and Values
  • Types
  • Functions with Multiple Parameters
  • Defining Functions
  • Function Signatures
  • Organizing Functions

#2 Mathematical Functions

Functional programming, its paradigms and its origins, are all rooted in mathematics. A mathematical function looks something like this:

Add1(x) = x + 1

  • The set of values that can be used as input to the function is called the domain.
  • The set of possible output values from the function is called the range.
  • The function is said to map the domain to the range.

If F# the definition would look like this.

let add1 x = x + 1

The signature of the function would look like this.

val add1 : int -> int

Key Properties of Mathematical Functions

  • A function always gives the same output value for a given input value.
  • A function has no side effects.

Pure functions

  • They are trivially parallelizable.
  • I can use a function lazily.
  • A function only needs to be evaluated once. (i.e. memoization)
  • The function can be evaluated in any order.

Prospectively “Unhelpful” properties of mathematical functions

  • The input and output values are immutable.
  • A function always has exactly one input and one output

#3 Function Values and Simple Values

Looking at this function again:

let add1 x = x + 1

The x means:

  • Accept some value from the input domain.
  • Use the name “x” to represent that value so that we can refer to it later.

It is also referred to as x is bound to the input value. In this binding it will only ever be that input value. This is not an assignment of a variable. Emphasis on the fact that there are no “variables”, only values. This is a critical part of functional thinking.

Function Values: this is a value that provides binding for a function to a name.

Simple Values: This is what one might think of as constants.

let c = 5

Simple Values vs. Function Values

Both are bound to names using the keyword let. The key difference is a function needs to be application to an argument to get a result, and a simple value doesn’t, as it is the value it is.

“Values” vs. “Objects”

In F# most things are referred to as “values”, contrary to “objects” in C# (or other languages like JavaScript for that matter). A value is just a member of a domain, such as a domain of ints, string, or functions that map ints to strings. In theory a value is immutable and has no behavior attached to it. However in F#, even some primitive values have some object-like behavior such as calling a member or property with dot notation syntax like “theValue”.Length or something similar.

Naming Values

Most of the naming is the general ruleset that applies to practically every language. However there is one odd feature that comes in handy in some scenarios. Let’s say you want to have a name such as “this is my really long and flippantly ridiculous name” for a domain. Well, what you can use is the “this is my really long and flippantly ridiculous name“ to have that be the name. It’s a strange feature, but I’ll cover more of it in subsequent articles.

In F# it is also practice to name functions and values with camel case instead of pascal case (camelCase vs. PascalCase).

#4 How Types Work with Functions

Function signatures look like this, with the arrow notation.

val functionName : domain -> range

Example functions:

let intToString x = sprintf "x is %i" x  // format int to string
let stringToInt x = System.Int32.Parse(x)

Example function signatures:

val intToString : int -> string
val stringToInt : string -> int

This means:

  • intToString has a domain of int which it maps onto the range string.
  • stringToInt has a domain of string which it maps onto the range int.

Primitive Types

Standard known types you’d expect: string, int, float, bool, char, byte, etc.

Type Annotations

Sometimes type might not be inferred, if that is the case, the compiler can take annotations to resolve type.

let stringLength (x:string) = x.Length   
let stringLengthAsInt (x:string) :int = x.Length 

Function Types as Parameters

A function that takes other functions as parameters, or returns a function, is called a higher-order function (sometimes abbreviated as HOF).

Example:

let evalWith5ThenAdd2 fn = fn 5 + 2 

The signature looks like:

val evalWith5ThenAdd2 : (int -> int) -> int

Looking at an example executing. The example:

let times3 x = x * 3
evalWith5ThenAdd2 times3

The signature looks like:

val times3 : int -> int
val it : int = 17

Also these are very sensitive to types, so beward.

let times3float x = x * 3.0
evalWith5ThenAdd2 times3float

Gives an error:

error FS0001: Type mismatch. Expecting a int -> int but 
              given a float -> float

Function as Output

A function value can also be the output of a function. For example, the following function will generate an “adder” function that adds using the input value.

let adderGenerator numberToAdd = (+) numberToAdd

Using Type Annotations to Constrain Function Types

This example:

let evalWith5ThenAdd2 fn = fn 5 +2

Becomes this:

let evalWith5AsInt (fn:int->int) = fn 5

…or maybe this:

let evalWith5AsFloat (fn:int->float) = fn 5

The “unit” Type

When a function returns no output, it still requires a range, and since there isn’t a void function in mathematical functions this supplants the void as return output. This special range is called a “unit” and has one specific value only, a “()”. It is similar to a void type or a null in C# but also is not, in that it is the value “()”.

Parameterless Functions

For a WAT moment here, parameterless functions come up. In this example we might expect “unit” and “unit”.

let printHello = printf "hello world" 

But what we actually get is:

hello world
val printHello : unit = ()

Like I said, a very WAT kind of moment. To get what we expect, we need to force the definition to have a “unit” argument, as shown.

let printHelloFn () = printf "hello world"

Then we get what we expect.

val printHelloFn : unit -> unit

So why is this? Well, you’ll have to dive in a little deeper and check out the F# for fun and profitThinking Functional” entry on “How Types Work with Functions” for the full low down on that. Suffice it I’ve documented how you get what you would expect, the writer on the site goes into the nitty gritty of what is actually happening here. Possibly, you might have guessed what is happen already. There is also some strange behavior that takes place with forcing unit types with the ignore function that you may want to read on that article too, but if you’re itching to move on, and get going faster than digging through all of this errata, keep going. I’m going to jump ahead to the last section I want to cover for this blog entry of notes, currying.

#5 Currying

Haskell Curry

Haskell Curry

Breaking multi-parameter functions into smaller one-parameter functions. The way to write a function with more than one parameter is to use a process called currying. For more history on this check out Haskell Curry the mathematician to dive deep into his work (which also covers a LOT of other things beside merely currying, like combinatory logic and Curry’s paradox for instance).

Basic example:

let printTwoParameters x y = 
   printfn "x=%i y=%i" x y

This of course looks neat enough right? Well, if we look at the compiler rewrite, it gets rather interesting.

let printTwoParameters x =
   let subFunction y = 
      printfn "x=%i y=%i" x y
   subFunction

That Non-Windows Scaffolding for OS-X and Linux |> I Broke It! But…

I dove into the ProjectScaffold solution recently to see where I could get with this project. Just like in the instructions I first cloned the project.

git clone

Then executed the shell script to get an appropriate download of Paket and related tools.

$ ./build.sh

On OS-X my first attempt I got scaffolding but a bad build right off. See the video below for that example.

Trying the same thing on Ubuntu gave me this issue. This issue seemed to be different from the OS-X issue so I’m working to resolve it separately.

adron@ubuntu ~/C/ProjectScaffold> ./build.sh
No version specified. Downloading latest stable.
Github download failed. Try downloading Paket directly from 'nuget.org'.
Error getting response stream (Write: The authentication or decryption has failed.): SendFailure

Then trying it on OS-X gave me this issue.  :-/

Grumble grumble, fuss, fuss, alright, going into debugging and troubleshooting mode. I made a video of the exact steps I went through.

So if you have any ideas, let me know, I’m currently looking through the code and trying out some things. Once I get this working I’ll update this blog entry below the video with the updated resolution. Thanks!

UPDATED: Dammit, the dumbest things are what always punch me in the face the hardest. I fixed it, and it didn’t require a pull request after all! When naming a project be sure to use only string characters to be safe. As I wrote in the github issue, the name “sharp-kata-01” breaks the build in a way that gives completely erroneous messages. Once I renamed it things moved forward.

Polyglot Conf 2015 Highlights & High Level Notes

A few highlights from Polyglot Conf 2015

JavaScript State of the Union

I didn’t actually plan to record this session, but whipped out the iPhone 6 and figured I’d give it a go. I ended up just recording the entire session. This is basically a level set and review of where and what’s up with the voluminous amount of JavaScript Frameworks, but everybody delves into a number of other things too. The sound is a little rough, but crank it up and you’ll be able to hear everybody speaking just fine.

Type Providers – Type Systems – Haskell and Conversations

I had more than one conversation, and listened in on more than a few. There was a LOT of hard core knowledge getting discussed and ideas for the future of languages. Everything from F# Type Providers (read more) to Haskell’s Type Safety and the lack there of. Also a few tidbits about building type providers. There was also some pretty big conversations around monolithic and micro-services.

Check out Martin Fowler’s write up on Monolith First.

I also got to chat with Elana Popovici about her workshop on Science Driven Decision Making, which delved into decision making around statistical analysis and related topics. The other workshop that I wish I’d been able to attend, but at least got to catch up with @BrianDorsey and @tavisrudd for a short time and discussed their Docker & Kubernetes workshop.

To be prepared for next years conference, follow the @PolyglotConf twitter account and be sure to get your tickets early, it tends to sell out.

Vancouver Itself

Polyglot Conference is held yearly in beautiful Vancouver BC. I don’t say Vancouver BC is beautiful just because I’m writing filler junk, this is, without question one of the most beautiful cities on earth along with being one of the most organized and well designed cities on Earth. It is, simply, impressive on a number of fronts. So if you know anything about cities, this is definitely one to visit and admire.

Even if beautiful cities aren’t your thing, Vancouver has an ever increasing array of great breweries, places to explore (in the city and outside), and a host of other places to check out that just add to the atmosphere of the conference itself.

Other benefits of being in Vancouver early for Polyglot conf.

OpenStack Conference

This year, the OpenStack 2015 had a stop in Vancouver, and this year that was great for me too. Even though I didn’t actually go attend the conference I got to meet a number of people in town for that conference since I came into town a few days early for Polyglot Conference.

Now, the OpenStack space is all fine and dandy, but it’s also a political field of landmines. So I’m always glad to just reap the benefits and not go wandering around in that space. I’m perfectly happy sitting above the OpenStack layer and working on applications and systems level operations that are a bit higher in the stack. So, thanks to all those that fight their way through all of that for us DevOps Coders that tend to stay higher in the stack. Kudos to all of you fighting that battle to make OpenStack awesome!

For some background on the war stories, check out

Rabbit MQ

Speaking of happenstance and such I got to meet @michaelklishin thanks to @lenadroid. Thanks for that introduction!

Michael and I dove into topics ranging from Cloud Foundry to Rabbit MQ, both things you may know of as Pivotal efforts these days. It just so happened I’ve got a little Cloud Foundry history and am working on using or implementing both on a current contract job I’m doing.

It was good conversation and if you’re into similar things definitely give Michael a follow on twitter and github. He’s also pretty involved in a bunch of OSS work (including of course Rabbit MQ and related) so dive in and introduce yourself.

Summary: I’m already aiming to be there, looking forward to more solid discussion and prospectively putting together a workshop myself and prospectively getting a little hacking festival going on pre- or post- conference.

Want to Go To the Progressive .NET Conference in London?

…but you just need a ticket? Well here’s the deal. I’ve got a ticket, it fell from the tree of random tickets and I shall make it free to one who might want to go. Here’s the smallest catch that I have…

I want to have some extra demo code to show during my presentation on Visual Studio & .NET on OS–X, Linux, and Windows, and I’d love to talk somebody’s demo code up during my presentation. So throw together some demo code in C# or F# that shows something cool, mathematically crazy, or something else that’s interesting to you. This is up to you, so get some code committed to github and ping me with the repo. I’ll hook you up with a ticket to the Progressive .NET Conference in London the 1st, 2nd AND 3rd of July. The way to submit the code is super easy, this really shouldn’t take more than about 20-30 minutes for a ticket that is worth £395, which is over $600 bucks in US dollars – just sayin’, weak US dollar to the British pound and all!

Here’s the rules:

  1. You must submit the code to me before June 26th so I can get it thoroughly tested, because YES I will demo with it and give you a shout out.
  2. It must be in a simple C# or F# project that is either a console app or just a library that has tests for it that shows or describes what it is doing. (If you do this, I might even throw in another $100 bucks just because you wrote tests!)
  3. Put the code in a git repo, and push it up to github. I’ll check it out and declare a winner on the 27th of June.
  4. Ping me on twitter @Adron.

See you at Prog Net Conf 2015!

Progressive .NET Tutorials 2015

I’ll be Speaking @ Progressive .NET Tutorials in July

Why

Recently Microsoft has really gotten it’s act together, at least for those of us that really love some of the Microsoft tools, but really don’t want to touch Windows. I’m perfectly happy not dealing with Windows, so this has been great news for me.

With the recent Build event Microsoft released Visual Studio Code, which is a fully cross-system compatible IDE that is lean, fast, and allows for building software with multiple languages. Of course, it works with several .NET languages such as F# and C#, and even will let you dive heavily in JavaScript Node.js based applications. I wrote a quick “Notes From the Front: 5 Minutes With Visual Studio #Code” a short while ago. Along with that I wrote “OS-X and F# [Clone It, Build It, Install It, Hack It]” and “Why F#, and Why Not Windows” as a follow up to this new growing world of Microsoft options.

Now, don’t get me wrong, Windows definitely has some plusses. It just isn’t the system I’d prefer these days, as it doesn’t hack it in the startup lands of Silicon Valley, Portland, Seattle, Vancouver BC, or other such places. In these lands, people speak and work with the *nix landscape first, and everything else is secondary. But that doesn’t remove the desire I have for applications, devices, and other tooling that enables compatibility across all of these systems.

With those thoughts, I sat down and started putting together some presentations on what’s possible with this new freedom around Microsoft tooling. Already I’d worked pretty extensively with Node.js and the tooling Microsoft has added to Visual Studio, Azure, and all those related things. Now I’m looking forward to checking out some of the other capabilities around F#, and the respective API options and other new OSS technologies like Akka .NET, and even M-brace. So here’s the gist of my presentation so far, and as I give this talk I’ll provide other related information on the page I’ve setup for the talk here.

Presentation Title: Visual Studio & .NET on OS–X, Linux, and Windows

From the inception of Mono on through to today’s Omnisharp and the introduction of Visual Studio Code at Build 2015. I’ll take a look at where cross-platform compatible solutions have been and where we are now with code samples along the way with some discussion on mobile topics too.

I’ll be adding a bit more to this also, and will have the demos and related code samples located here.

Who, What, When, Where

So where am I giving this presentation? Check out Progressive .NET Tutorials 2015 for more information. The conference is in London and I’m officially on the program page (so obviously I’m going eh!). They haven’t released the exact time of each talk, but what you should do is just come attend the whole conference! I’ll be speaking on the 3rd. The location of the conference is in the grand city of London, located specifically at this fine establishment.

I’ll have more about the conference and other technical tidbits in the near future. Very soon I will also be announcing a chance to win a ticket to Prog .NET Tutorials, so stay tuned, subscribe, and follow me on Twitter @adron for more info.

Simplifying bash & repl Use With F#

That prompt… let’s get F# so that we can compile and run a file in about a zillionth of a second from the repl.

First I setup a bash script that would be used to compile and then run the file. I created the file and simply named it “fs”. Inside the file I wrote the following script.

echo "Compiling F#" + $1
fsharpc "$1.fs"
mono "$1.exe"
echo "Running Executable" + $1

I put that in my scripts folder that I have added to my path in my ~/.bash_profile (or bashrc depending on what you’re rolling with).

export PATH="$PATH:~/Codez/scripts"

So now I have the ability to type in the following command and filename and the compile and the executable will be run. It makes for much easier repl usage.

fs theFileNameGoesHere

Got any tips or tricks to running F# somewhere besides Windows? Let me know and I’ll be sure to give you a shout out on Twitter and whenever I’m giving a presentation on hacking F# without Windows.

Why F#, and Why Not Windows

I posted my previous entry and got a few retweets and favorites. One reply came back and made me think, “ah, it might not be obvious why I’d like to have F# on something besides Windows.” Well, here’s a list of why I want to use F# on non-Windows platforms.

  1. F# is a good language. I can’t say the best, since I honestly don’t have enough experience with it or other functional languages to really declare a victory in my opinion. However I’ll be doing some work with Scala, Haskell, and Erlang in the next couple of weeks for testing and use with some upcoming projects.
  2. There are only two technology stacks that will let one spin up an actual application on all of these technologies: OS-X Cocoa, Windows, Linux, Android, and iOS. These two tech stacks are .NET and than the Node.js JavaScript stack – with the latter being purely web based. (Yes, some could argue Adobe’s tools or the Java stack, but I’m not going down that route right now, as both are somewhat bloated and convoluted in ways we can go into at some other time)
  3. With F# I get a clean functional language that I can build native mobile, tablet, or OS apps and all the web services that I want with two advantages over Node.js. The first is the performance edge and can likely be tuned more anyway. Being paired with SignalR one can even get some wicked simple and fast real-time capabilities with minimal code. The second is it takes less F# code to do similar JavaScript things and compute, let me tell you about compute with F#. F# can run things that JavaScript just really can’t measure up to when it comes to compute. But aside from these things, they’re both excellent tools and I wanted to have F# in my tool belt.
  4. There’s always the backup plan of just converting to JavaScript too, if I needed that sort of thing. Check out FunScript.
  5. The community around F# is actually pretty cool, there are good, solid, intelligent, and friendly people in that community. Having a good community of people always makes getting into a new language or related tech much better then when the community consists of asshats or jack ass savants.

Other great things that add to the usefulness of F# include WebSharper.NET MVC 5 and Web API, Nancy API, Suave.io, and there are others.

So those are the reasons I decided to move forward with F#: solid language, provides a solid technical stack with options, it’s functional and clean with extra compute power, and a kick ass community. Of course F# came from the land of Windows and Softies (that’s short for Microsofties, and I didn’t make that up). But F# was handed over to the open source community and currently moves forward autonomously of Microsoft. By proxy of this event, and other culminating events of late, F# can easily run on operating systems besides Windows. I’m not a fan of Windows, and here’s a few snarky (yet very real) reasons why I don’t even want to mess with Windows (except in the situation where I really do want to or need to use Visual Studio).

  1. Windows is still slow. I could go into the reasons, but it tends to build slow, behave slow, be prone to the attention of spammers and such, only in the last X years has it managed security in a half ass decent way, which also leads to slowness, and … oh you get the idea. It’s a slow OS.
  2. It’s flippin’ humongous. Now is this really a problem? Not really, but it’s annoying to force fit it in when I’m doing DevOps work or actually attempting to load Windows related images with it. The OS itself is still a nightmare of gigantic proportions compared to spooling up other systems. If one wants to fight with it, that’s great, I don’t really feel a keen desire to fight with it.
  3. Linux == Smaller footprint, more features, let’s not bring up security, is actually used on major systems, large scale systems and super-computers. Windows has less than 2% market share in that space. Even Microsoft is decreasing their reliance on Windows, offering oodles of Linux options.
  4. Windows doesn’t tend to get, run, or have the bleeding edge tech options built for it. Go look at the open source massive distributed systems applications and other excellent leading platforms and tooling that are leading companies into the future. If Windows is involved at all, it’s often an afterthought. :-/
  5. Windows 8 interface. I’m just going to leave that one right there. I like a lot about it, but I’m with Microsoft, even with Windows 10 they’re not trying to push this UI/UX catastrophe any longer.
  6. SSH not built in. End of story.

Don’t get me wrong, the tooling on Windows for doing Windows specific development and even doing crud apps with lots of business rules is spectacular. I’d even bet that the .NET ecosystem does a better job, sometimes dramatically better, than the Java ecosystem when it comes to those types of applications. I however, haven’t built these style of applications in a long while. Whenever I do, Windows might be a prime option, but otherwise I’ll stick to the operating systems that get me into the coding faster, sooner, and with less resistance.

Outside of Windows there are a lot of great Microsoft tools and technologies that I’d love to have on non-Windows operating systems. One of those is F#. Another is Visual Studio, which I’m betting will continue to get better and better. I’d like to have C# (which I do with Xamarin and such) and a whole ton of other scaffolding and crud tools and other things that are available. I just prefer them without Windows.

As I often say, to each their own. Mine just isn’t Windows these days.