F# -- the 3 minute guide!
secretGeek .:dot Nuts about dot Net:.
home .: about .: sign up .: sitemap .: secretGeek RSS

F# -- the 3 minute guide!

By popular demand, we're going to spend three minutes learning as much as we can about F#.

So what is F#?

F# is "a mixed functional/imperative/object-oriented programming language"

Sorry -- that description's meaningless to all but a handful of people. What I want to know is:

Is F# really "Fortran .Net?"

No! An earlier name for F# was: "Caml.Net" because this is essentially a ".Net" implementation of "Caml"

That doesn't help, unless you know what Caml is...

Caml is a popular French variation on the ML Programming language, where ML means 'meta-language'.

Then I take it F# has nothing to do with Sharepoint's Caml language?

Nothing whatsoever. It's unfortunate that the sharepoint team used that name. Enough said.

You know what? Let's just get our hands on the code...

(Continues)

If you've got the .Net Framework version 2.0, then all you need is F#:

Download and unzip. You'll have a nice folder full of goodies.

As you can see there's an ".MSI" (microsoft installer file) included. Run that... and things should go smoothly.

(Oh wait... some problem with a missing file... a html file? Who cares? Ignore!)

It installs an interactive console, a visual studio plug in, a manual, release notes and samples.

Let's tinker with the F# Visual Studio plugin

Open visual studio 2005, go to the tools menu, "add in manager" -- and click the interactive F# tool, to load it.

Now there's a new tool window, not unlike the 'immediate window' that we know and love.

It contains this chunk of text:

MSR F# Interactive, (c) Microsoft Corporation, All Rights Reserved
F# Version 1.1.11.12, compiling for .NET Framework Version v2.0.50727

NOTE:
NOTE: Flags: --gui run a session with a GUI event loop.
NOTE: --exec just run the scripts on the command-line.
NOTE: Commands: #r <string>;; reference (dynamically load) the given DLL.
NOTE: #I <string>;; add the given search path for referenced DLLs.
{{blah, blah blah}}
NOTE: Bug reports to fsbugs@microsoft.com. Enjoy!
NOTE:
NOTE: Visual Studio key bindings:
NOTE:
NOTE: Up/Down = cycle history
NOTE: CTRL-C = interrupt session
NOTE: ALT-ENTER = send selected source text to FSI session (adds ;;)


I always like to skip past the rather bland hello world programs and straight onto my personal favourite:

> do print_endline "hello there ladies ;-)" ;;

hello there ladies ;-)
>

That certainly worked a treat. Not exactly inspirational stuff though.

Two crucial lessons in there: "do" calls a function, while ";;" seems to terminate a statement.

Never happy with just one implementation, i hit upon another way to achieve the same result...

I open a blank text file (in Visual Studio) and type the following:


do printf "ahh, we meet again\n"


I highlight this text and hit "[Alt] + [Enter]"

Magically, the output turns up in the interactive F# window!

Were you paying attention that time? I didn't type into the F# window. You can type in any window at all (within visual studio). Then highlight the text and press alt-enter. The highlighted text is evaluated by the f# interactive tool. Nifty stuff.

Functions! Hurry Up with the Functions!

Oh, you want me to write a function in this functional language... yes i was hoping to avoid that.

Okay -- now I've written "My First Function" in F#, here it is:


let NextNumber x = x + 1

What I'm hoping this means is:

"Let me define a function called 'NextNumber' that takes an input, x, and returns x + 1"

When I select the text of my little function, and hit Alt-Enter, the following text appears in the interactive window:


val NextNumber : int -> int

This is the 'signature' of the function, more or less. It means something like:

"the 'value' NextNumber takes an integer as input and outputs an integer."

Fair enough. Now from the smidgen I know about functional programming, i know they do love their recursive functions. I soon find this keyword rec, meaning recursive, which can be used for any function that defines it's output in terms of its input.

You'd prefer an example? Well let's write a function that adds up all the numbers from 1 to X.

And let's do it using recursion.


let rec sumto n =
  if n < 2 then 1
  else n + sumto(n-1);;

This one basically says:

"Let me define a recursive function called 'sumto', that takes the input n. If n is less than 2 then return 1, otherwise return the value (n + sumto ( n - 1)). ."

Okay, now we can use our function like so:


sumto 100

Which returns the following result in the interactive window:


val it : int = 5050


(Twenty minutes on the calcu'later, i can confirm this to be correct.)

Notice that both the function we wrote earlier and this result we've just calculated are described as 'values'. I take this to be a sign of the way a functional programming language treats functions as first class citizens.

Now I can jump to something I've been wanting to demonstrate since the start. The |> operator. Let me put that in a heading:

The Pipeline Operator, |>

That's a bar symbol, followed by a greater than. And it's similar to the pipe operator you recall from your DOS-filled youth.

Instead of typing 'sumto 100', as we did above, we could pipe the parameter into the function, like so:


100 |> sumto //returns the same values as 'sumto 100'... i.e.
val it : int = 5050

Here we've said something like: "direct the value 100 into the value 'sumto'"

We can use this logic to re-write the 'sumto' function from above:


let rec sumto n =
if n>1 then
n + (n-1 |> sumto)
else 1

What's so important about this |> operator? Isn't it just a redundant little syntactic bit of acrobatics?

Yes and no, old buddy. Yes and no.

Imagine some deeply nested function calls, like so:

a(b(c(d(10)))) ;;

You've got to admit that it looks ugly, but also that it's horribly ass about. [That's a technical term for back-to-front].

"a(b(c(d(10))))" means "apply the function d to the value 10, then apply the function c to the result of that, then apply the function b to the result of that... and so on."

A less ass-about syntax is:

10 |> d |> c |> b |> a ;;

The above code could be described as "direct the value 10 into the function d, then direct the result of that into the function c, then..." and so on.

It's easy to match the code with the description of what's happening. Or at least, easier than it would be if we used the original ass-about syntax ('a(b(c(d(10))))')

(I fully expect that the preceeding pipeline operator description is completely wrong... I await a clarification from don syme, of course ;-) )

Okay -- that's as far as we can possibly get in three minutes. We didn't have as much fun with curry as i'd have liked.

I'll finish with some links for the intrigued reader:

F# links:

The best place to start: Quick Tour -- almost a cheat sheet.

resources

articles:





'Mike Gale' on Sun, 27 Aug 2006 19:14:29 GMT, sez:

I guess your comment about 20 minutes on the calculator was for effect.

(100 + 1) * 50 = ?



'lb' on Sun, 27 Aug 2006 19:17:32 GMT, sez:

i know mike...

let fun sumto n = n * (n+1) /2

i wanted to have a recursive function that would stack overflow before it overflows its values so i opted for this over factorial or fibonacci... it's purely a teaching example ;-)



'Daniel' on Mon, 28 Aug 2006 04:57:07 GMT, sez:

Sum t 100 goes like this:
1 + 100 +
2 + 99 +
3 + 98
...
So basically it's 101*50. Mr. <a href="http://en.wikipedia.org/wiki/Carl_Friedrich_Gauss">Gauss</a> came up with this when he was a little boy.



'lb' on Mon, 28 Aug 2006 05:13:17 GMT, sez:

I don't know about Gauss, but this is how i calculated it when i was but a wee lad (of fifty six). And this is still how i picture it:

You have a rectangle of height N and length N+1. Divide the area by two: and this will give you the sum of all the numbers from 1 to N, like so:

sum from 1 to N

'Daniel' on Mon, 28 Aug 2006 06:14:56 GMT, sez:

Considering Gauss became famous for his solution, you should be up there right with him! ;-)



'piggy' on Mon, 28 Aug 2006 22:29:18 GMT, sez:

lb, this is really a vivid graph with sophisticated idea. Well done.



'Simon' on Tue, 29 Aug 2006 06:45:51 GMT, sez:

Another great "quick guide". Do a few more of these and you could publish a book. "Learn 24 languages in 24 hours" or something.



'lb' on Wed, 30 Aug 2006 00:40:45 GMT, sez:

cheers Simon. re: "Learn 24 languages in 24 hours"
would be fun to write, but it'd be out of date before it was in the shops.

I have other ideas for books of course ;-)



'Dominic Cooney' on Thu, 31 Aug 2006 01:09:17 GMT, sez:

What's your next F# project?



'lb' on Thu, 31 Aug 2006 01:14:53 GMT, sez:

ahhh! the Japanese Cooney! i don't have any F#'s projects at all... i'd be interested in doing something in F# of course, but it's just for fun right now.



'Don Syme' on Tue, 19 Sep 2006 14:13:58 GMT, sez:

For those who want to go into more depth, a draft of Chapter 2 of "Expert F#" ahs been published at http://cs.hubfs.net/blogs/f_team/archive/2006/09/07/586.aspx.



'lb' on Mon, 30 Oct 2006 23:34:04 GMT, sez:

look! ^^ a comment from Don Syme.

And he didn't bag me for my bad and innaccurate description of his language!!

go don!



'Mike Hadlow' on Mon, 18 Dec 2006 07:24:43 GMT, sez:

Hey Leon I've been playing with F# too! I'm really excited about functional programming. I think it could add as much as OO did to my programming skills although it's like standing at base camp looking up at Everest right now. Do you know you can rewrite your recursive example in a more functional-ish way with a match:

let rec sumTo x =
match x with
| 0 -> 0
| n -> n + sumTo(n-1)



'lb' on Mon, 18 Dec 2006 08:50:26 GMT, sez:

nice stuff Mike.

this is a kind of pattern matching example you've got there isn't it? that's my second favourite thing about functional languages, and i think it's the feature most stealable for adding goodness to imperative languages.



'Hamlet D'Arcy' on Sun, 13 Jul 2008 15:32:00 GMT, sez:

The pipeline operator is also useful because the type inference in the F# compiler works from left to right in your code. Property access and method overloading will sometimes require you to specify some types for the parameters to resolve ambiguity, but if you use the pipeline operator then that ambiguity can be erased.

It ain't just a pretty way to invoke functions!

Information taken from Syme's Expert F#.




name


website (optional)


enter the word:
 

comment (HTML not allowed)


All viewpoints welcome. Incivility is not tolerated, such comments are deleted.

 

I'm the co-author of TimeSnapper, a life analysis system that stores and plays-back your computer use. It makes timesheet recording a breeze, helps you recover lost work and shows you how to sharpen your act.

 

NimbleText - FREE text manipulation and data extraction

NimbleText is a Powerful FREE Tool

I wrote this, and use it every day for:

  • extracting data from text
  • manipulating text
  • generating code

It makes you look awesome. You should use NimbleText, you handsome devil!

 

Articles

The Canine Pyramid The Canine Pyramid
Humans: A Tragedy. Humans: A Tragedy.
ACK! ACK!
OfficeQuest... Gamification for the Office Suite OfficeQuest... Gamification for the Office Suite
New product launch: NimbleSET New product launch: NimbleSET
Programming The Robot from Diary of a Wimpy Kid Programming The Robot from Diary of a Wimpy Kid
Happy new year 2014 Happy new year 2014
Downtime as a service Downtime as a service
The Shape of Your Irrationality The Shape of Your Irrationality
This is why I don't go to nice restaurants any more. This is why I don't go to nice restaurants any more.
A flowchart of what programmers do at work all day A flowchart of what programmers do at work all day
The Telepresent Man. The Telepresent Man.
Interview with an Ex-Microsoftie. Interview with an Ex-Microsoftie.
CRUMBS! Commandline navigation tool for Powershell CRUMBS! Commandline navigation tool for Powershell
Little tool for making Amazon affiliate links Little tool for making Amazon affiliate links
Extracting a Trello board as markdown Extracting a Trello board as markdown
hgs: Manage Lots of Mercurial Projects Simultaneously hgs: Manage Lots of Mercurial Projects Simultaneously
You Must Get It! You Must Get It!
AddDays: A Very Simple Date Calculator AddDays: A Very Simple Date Calculator
Google caught in a lie. Google caught in a lie.
NimbleText 2.0: More Than Twice The Price! NimbleText 2.0: More Than Twice The Price!
A Computer Simulation of Creative Work, or 'How To Get Nothing Done' A Computer Simulation of Creative Work, or 'How To Get Nothing Done'
NimbleText 1.9 -- BoomTown! NimbleText 1.9 -- BoomTown!
Line Endings. Line Endings.
**This** is how you pivot **This** is how you pivot
Art of the command-line helper Art of the command-line helper
Go and read a book. Go and read a book.
Slurp up mega-traffic by writing scalable, timeless search-bait Slurp up mega-traffic by writing scalable, timeless search-bait
Do *NOT* try this Hacking Script at home Do *NOT* try this Hacking Script at home
The 'Should I automate it?' Calculator The 'Should I automate it?' Calculator

Archives Complete secretGeek Archives

TimeSnapper -- Automated Screenshot Journal TimeSnapper: automatic screenshot journal

25 steps for building a Micro-ISV 25 steps for building a Micro-ISV
3 minute guides -- babysteps in new technologies: powershell, JSON, watir, F# 3 Minute Guide Series
Universal Troubleshooting checklist Universal Troubleshooting Checklist
Top 10 SecretGeek articles Top 10 SecretGeek articles
ShinyPower (help with Powershell) ShinyPower
Now at CodePlex

Realtime CSS Editor, in a browser RealTime Online CSS Editor
Gradient Maker -- a tool for making background images that blend from one colour to another. Forget photoshop, this is the bomb. Gradient Maker



[powered by Google] 

How to be depressed How to be depressed
You are not inadequate.



Recommended Reading


the little schemer


The Best Software Writing I
The Business Of Software (Eric Sink)

Recommended blogs

Jeff Atwood
Joseph Cooney
Phil Haack
Scott Hanselman
Julia Lerman
Rhys Parry
Joel Pobar
OJ Reeves
Eric Sink

InfoText - amazing search for SharePoint
LogEnvy - event logs made sexy
Computer, Unlocked. A rapid computer customization resource
Aussie Bushwalking
BrisParks :: best parks for kids in brisbane
PhysioTec, Brisbane Specialist Physiotherapy & Pilates
 
home .: about .: sign up .: sitemap .: secretGeek RSS .: © Leon Bambrick 2006 .: privacy

home .: about .: sign up .: sitemap .: RSS .: © Leon Bambrick 2006 .: privacy