A couple of questions left

Now, I have some time to write about a couple of questions I have received about F#, and their answers.

1. To get a specific element of a tuple :

If we do not want to create variables for the elements that we are not interested in of a tuple, we can use “_” for all other elements, i.e.:

let drinks= (Coke, 0.45, “Coca Cola Zero”)
let _, _, valBrand= drinks

which is interpreted into the compiler as we see in the FS Interactive window:

val drinks : string * float * string = (“Coke”, 0.45, “Coca Cola Zero”)
val valBrand : string = “Coca Cola Zero”

2. “namespace” keywords stays as is, and we can have either a module or a type [i.e. C# class] under a namespace. The example would be :
File1: Drink.fs

namespace Vesta.Beverage
module Drink=
let drinks= (Coke, 0.45, “Coca Cola Zero”)
let _, _, valBrand= drinks

File2: BeverageCalculator.fs [placed under the Drink.fs if they are in the same project.]

namespace Vesta.Calculator
open Vesta.Beverage.Drink
module BeverageCalculator=
let drink= valBrand

So, we can use everything from the first namespace,
Happy F# days!

Comments from my First Talk at ldnUG about F#

First of all, thanks all who had their valuable time spent on my talk about F# at EMC Conchango.
Thanks to Michelle for beers, to Zi for finding an HDMI cable at the last minute, to Liam for lovely chocolate cakes, to Argos for support, and to everyone for coming…

It was my first talk in England, and as it was a public talk, I was not sure about the content, examples. Even if I am coming from a trainer background, and I know that different level of people had attended my .NET Courses, it was quite hard to decide the depth of the subject, and to deliver the message I want to deliver. Every decision has a drawback, going simple can bore people, whereas going into complicated scenarios can leave some people out.
Rather than taking the challenging option :
– I decided to name the talk as “Intro”, so I thought meeting the expectations would be easier.
– Rather than going theoritical and covering more aspects of F#, I wanted to go over a simple demo, and share the feeling of writing in F# with VS2010.

Thanks God, it was not a disaster, and I got comments to work on, and improve, which is always good.

1. A complete sample:
My presentation was missing a complete sample, as my demos were quite small sized examples. When the seminar finishes, the audience would have felt more satisfied, if I had started and finished an F# project.
I had thought about this beforehand, but was not sure if I could have a project which is “simple” enough so that the audience can follow, “clean” enough so that I do not have to hacks during demo, and “complex” enough so that the audience would take home and work at home. I admit it is hard, but not achivable.

2. The balance of the slides/demo
Interestingly I got a feedback telling that I was better when I was coding during the presentation, and this was quite unusual for user group events; and I got feedbacks telling that I was disconnected from the audience while I was coding, so my mood/excitement was negatively affecting my touch to keyboard, and I was seen more confident while I was doing the talk and answering the questions.
Making everyone happy is impossible of course, but I can take both feedbacks as sensible.  After seeing 50 people in the room, [full room, with people sitting on the edge of the window], my confidence has jumped out of the window, instead of myself. I reckon, the less perfection I am, the more communicator I will be.
I love coding, so coding during the whole session would be my pleasure, but there is the other feedback comes into the screen:

3. How well you know your keyboard/touchpad/mouse?
The audience does nothing but sits and watch your coding experience. Little tweaks, multiple corrections to your mistakes does make your audience confused and breaks their focus. Bringing a keyboard/mouse that you daily use is the suggestion and I will try to take this one. Working more on my new laptop is the other option, and is a good alternative obviously, but it would never replace my keyboard used 8-10 hours a day.
What happens is that they may either start to interest into something different or start to sleeping. Worse than that, they may start talking to each other. Talking more about what you do and doing less changes at a time, does keep everyone back on board.

4. Communicating contact details
As the questions can be tricky during the session, you may need to give the answers later. But if you have not included your contact details at the end of the presentation, there is a high probability that, you will forget to tell “I will post the answers to my blog as soon as possible” as I forgot.
If you have anything you want to add, please do!

F# vs C# Samples

After my talk at ldnUG yesterday, I got nice suggestions from Zi Makki, and here is the first one: comparison between F# and C#, especially using LINQ. This subject had been quite popular once in a while, now it is probably my time to focus on this subject. My initial samples are quite common: getting numbers less than 5 from a list, and getting files from a specified directory.

static void Main(string [] args)
{
List list= new List { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
LessThanFive(list);
}
private static void LessThanFive(List list)
{
string y = list
.Where(x => x <= 5)
.Select(z => z.ToString())
.Aggregate(” “, (seed, n) => seed + n);
}

If we want to write this in F#, List.filter will be enough for filter operation, and the List.iter will go through the list, and do any operation/function we define for each item in the list.

let lessThanFive list=
list
|> List.filter ((>=) 5) >>
|> List.iter (printfn “%d”)
let z = lessThanFive [1..9]

The second example if for printing the folder names
With the help of the extension method explained at stackoverflow, here is a better C# code to get the files of a specified path.

class Program
{
static void Main(string[] args)
{
Dir(@”C:\Program Files (x86)\Microsoft F#\v4.0″);
Console.ReadLine();
}

private static void Dir(string
{
Directory.GetFiles(path)
.ForEachWithIndex(
(item, idx) => Console.WriteLine(“{0}: {1}”, item, idx));
}
}
public static class ForEachExtensions
{
public static void ForEachWithIndex(this IEnumerable enumerable, Action <T,int> handler)
{
int idx = 0;
foreach (T item in enumerable)
handler(item, idx++);
}
}

And the F# version would be quite simple, as Array.iter is enough to process the array resulting from GetFiles:

let dir folder=
Directory.GetFiles folder
|> Array.iter(fun x-> printfn “%s” x)
let result= dir @”C:\Program Files (x86)\Microsoft F#\v4.0″

F# Samples

If you had the chance to start playing with F#, here are some nice challenges  for you. If not you may want to look at from where to start.

1. Dustin Campbell, has started Project Euler questions on his Yet Another Project Euler Series. There are 283 questions at the Euler project. To give the idea, here are the first three ones:
Problem 1:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

Problem 2:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
Find the sum of all the even-valued terms in the sequence which do not exceed four million.

Problem 3:

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?

2. If you are into numerical analysis, you may try Newton Basin Fractal, i.e. finding roos of a polynomical function in a complex plane, you can be inspired by Jonathan Birge did:

Image

3. Using Accelator Library, Tomas Petricek has some Game of Life example , which implements Conway’s Game of Life. There are some more including Calculating PI, Data Parallel. He is the co-autohor of Real World Functional Programming.

I am curios to hear from you, any suggestions/links you want to add?

Started F#

Where to start is the question, and here is a short intro from the best sources I could find:


1. Don Syme’s weblog

He is the creator of F#, and emphasizes the succint and expressiveness of the language.

F# makes three primary contributions to parallel, asynchronous and reactive programming in the context of a VM-based platform such as .NET:

(a) functional programming greatly reduces the amount of explicit mutation used by the programmer for many programming tasks
(b) F# includes a powerful “async” construct for compositional reactive and parallel computations, including both parallel I/O and CPU computations, and
(c) “async” enables the definition and execution of lightweight agents without an adjusted threading model on the virtual machine.


2. Chris Smith’s Programming F# book in 20 minutes Part I and Part II

Notes from the book:

* F# supports functional programming, tells what to do, not how to do.
* F# supports imperative programming

Example:

let functionalSum numbers =
  numbers
  |> Seq.map square
  |> Seq.sum

let imperativeSum numbers=
   let mutable total=0
   for i in numbers do
     let x= square i
     total <- total + x
   total

* F# supports OO programming, you can abstract the code into classes and objects.
* F# is a .NET language with all libraries, Garbage Collector, and CLI.
* Everything is immutable by default, so you can experience side-effect free development.
* F# is statically typed, at compile time you have the type-safe code.
* Take care of:
–  the order of the files of your project in your solution explorer, they will be compiled from top to bottom.
– indentations, as there are no curly brackets, the indentation will define the scope.
– also F# is white-space significant, and case-sensitive.


3. An introduction to F# at Channel 9 by Luca Bolognese. Notes from the presentation:

You went to counter, and told that you want a cappucino, and start to tell “Now you grind the coffee, and get the water, warm it. At the same time, prepare the milk, but I want those things go in parallel.”

Three key things he emphasizes:

1. let keyword bind a value to a symbol

let sqr x = x * x

2. Arrow “->”, similar to “=” in C# for assigning value; but it is more specific: it means you are pushing something inside the location in memory, not working with symbols any more.

let addBalance x=
    let balance =0.0
    balance <- balance + x 

3. fun: Function/lambda expression as in c#

(fun x->x+3) 7;;

which takes 7 as parameter and returns 10 or

List.map (fun i->i*2) [1..4]

which return [2,4,6,8]


4.Don Campbell’s blog about why he loves F#


5. The F# community, HubsFs


6. F# at Microsoft Research


7. Phil Trelford’s session at EdgeUG talk, with nice F# samples.

Anything I have missed?

VS2010 installation dissappointment

Yesterday I have installed my VS2010 RC, but did not work when I try to set F# as default settings, and try to open a new project [any project unfortunately]
The error message is :
“The project file ‘C:\Users\Ebru\AppData\Local\Temp\qxdqjrxq.oco\Temp\Library1.fsproj’ cannot be opened. because its project type (.fsproj) is not supported by this version of the application.
To open it, please use a version that supports this type of project.”

here is my screenshot…Image

How dissapointing is that I have to install R# Runtime separately…And to fix this you may re-run this exe and repair it.
Then, you may start your F# project.

And
Image