Showing posts with label f#. Show all posts
Showing posts with label f#. Show all posts

Monday, August 8, 2011

F# and the immediate window

(This post is inspired from this Stack Overflow question)



F# debugger integration is quite good, except for the immediate window. The immediate window requires C# style syntax, so calling F# functions is not intuitive. Below are recipes for the immediate window integrated into a console application. As always code can be found here:

// Learn how to use the immediate window for F#.
module Program=

// To build, add a reference to Microsoft.CSharp. This is required for dynamic support in
// the debugger.
let allowDynamicToWorkFromImmediateWindowByLoadingCSharpBinders = Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags.BinaryOperationLogical

let plusOne = (+)1
let xPlusOnes = [1;2;3] |> Seq.map plusOne

[]
let main (args) =
printfn "Try the following in the immediate window:
// plusOne 4
((dynamic)plusOne).Invoke(4)

// Seq.Head xPlusOnes
Microsoft.FSharp.Collections.SeqModule.Head(xPlusOnes)

// let xPlusTwos= xPlusOnes |> Seq.map plusOne
// Seq.Head xPlusTwos
var xPlusTwos = Microsoft.FSharp.Collections.SeqModule.Map(plusOne,xPlusOnes);
Microsoft.FSharp.Collections.SeqModule.Head(xPlusTwos)"

System.Diagnostics.Debugger.Break()
let returnValue = 1
returnValue

Friday, March 11, 2011

Using LINQ to XML from F# (and a bit of duck typing for fun)

So you want to use XML from F#? here are the tips and tricks I discovered today to clear my roadblocks.

Tip 1: Reference the System.XML assembly from FSI so you play with the REPL. To do this I add the #r in block comments at the top of the file  like so:

(* Press Alt-' to send the below to the interpreter.
#r @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Xml.Linq.dll"
*)
open System.Xml.Linq
Tip 2: F# doesn’t perform implicit conversions. Lets assume you’re translating the following C# code:

var xelements = XElement.Parse("<myXML/>");
var interestingElements = xelements.Descendants("myXML");
The naive translation below doesn’t work because XElement.Decendants doesn’t take a string, it takes an XName. 

//FAILS to compile This expression was expected to have type XName but here has type string 
let interestingElements = xelements.Descendants "myXML"
The reason the above code works in C# is because an implicit conversion operator exists and is called. However in F# implicit conversions are not called, and you have to call them yourself, something like the painful to read:

let interestingElements = xelements.Descendants <| XName.op_Implicit "myXML"; 
Now, it turns out we can use duck typing to make an implicit conversion operator (this is mentioned lots of places on the web but I’ll repeat it for succinctness)

// Create an implicit conversion operator, it's inline which means it will work on any types that support the implicit conversion.
// This is duck typing.
let inline convert_implicit(arg : ^source) : ^target = ((^source or ^target) : (static member op_Implicit : ^source -> ^target) (arg))
And finally we can write the code I needed:

let interestingElements = xelements.Descendants <|  convert_implicit "myXML"; 

Saturday, July 17, 2010

F# Tricks: Concise BoolToInt

As a C# programmer, you'd probably write BoolToInt as follows in F#:
	let boolToInt3 b = 
if b = true then
1
elif b = false
0


Not a big win over C# yet, but a few things to point out about the concise syntax: Indentation implies blocks. There is no 'return' keyword. This function is statically typed, you don't see types since the compiler infers the types.



As a novice F# programmer a trick you learn is pattern matching. Pattern matching is like a case statement, but it's an expression and it's really powerful. I'll go into more details on pattern matching in future posts. For now, notice the elegance of the below:



	let boolToInt2 b = 
match b with
| true -> 1
| false -> 0

Pattern matching is so useful to F# there is a syntax for creating a function of one parameter that only pattern matches, using that syntax, we define boolToInt in the final form of:

	let boolToInt3 = function 
| true -> 1
| false -> 0

Thursday, June 10, 2010

F# Tricks: Collecting Some Optional Values

Skip this post if you have no idea what F# is, and think LINQ is stupid.

When you map inputs to outputs with a function that can return None, or Some Output, you get an annoying issue of having a list containing Nones, and Somes. For example:

// Contains both encrypted and un-encrypted files: 
let listOfFiles:Seq

// Return a decrypted File, or None if the file can't be decrypted.
let decryptFile file
match file with
| isFileDecryptable file -> Some DecryptFile file
| _ -> None

// decryptedFiles contains Nones, intertwined with some Some DecryptedFiles
let decryptedFiles = listOfFiles |> Seq.map decryptFile
Here are two ways to remedy that:

// To get a list of only decrypted files you could do:
let realDecryptedFiles = decryptedFiles |> Seq.filter Option.isSome |> Seq.map Option.get

// However, I prefer the more concise version of:
let realDecryptedFiles = decryptedFiles |> Seq.collect Option.toList
If you're an F# guru I'd love to hear your thoughts on this.

Saturday, May 15, 2010

Making the FSharp interpreter (fsi) run in 64bit!

I love F#!  It’s all the power of functional programming with the training wheels of c# when you need it. All the prototype/REPL power of powershell and python, with the built in test cases I like to call static typing. All the power of static typing, with out the hassle of specifying types every where thanks to implicit typing.

But, there is one annoying problem, I crunch very large data sets and fsi.exe runs as a 32 bit application. This means when I load my data sets and iterate through them FSI takes up 1.6 GB of RAM (maximum for a 32bit app), and spends 100% of its time in GC.

An aside for you who are thinking: 1.6GB is enough RAM!? – Igor must be a really crappy programmer!!! 1.6GB could be plenty, but why should I spend time adding complexity to my code when I have a superb memory manager, a 64 bit address space and a 3 year old dev machine that has 16GB of RAM, and 8 processors?  Today, I get no value from optimizing my data set for memory utilization -- I’m better off making my data cruncher a 64 bit application.

Back to work.  First, lets open up the Visual Studio command prompt (it has the tools we need in its path) and find fsi.exe.

C:\Program Files (x86)\Microsoft F#\v4.0>dir fsi.*
Volume in drive C has no label.
Volume Serial Number is 8EDE-D64E

Directory of C:\Program Files (x86)\Microsoft F#\v4.0

03/19/2010 02:02 PM 230,216 Fsi.exe
09/30/2009 08:08 PM 158 Fsi.exe.config
2 File(s) 230,374 bytes

Lets make sure it's 32 bit - we do that with a tool called corflags.

C:\Program Files (x86)\Microsoft F#\v4.0>corflags fsi.exe
Microsoft (R) .NET Framework CorFlags Conversion Tool. Version 4.0.30319.1
Copyright (c) Microsoft Corporation. All rights reserved.

Version : v4.0.30319
CLR Header: 2.5
PE : PE32
CorFlags : 11
ILONLY : 1
32BIT : 1
Signed : 1

Next we use corflags to make fsi 64bit. This will unsign the fsi.exe but this hasn't affected anything for me yet.

 

C:\Program Files (x86)\Microsoft F#\v4.0>corflags /32bit- /force fsi.exe
Microsoft (R) .NET Framework CorFlags Conversion Tool. Version 4.0.30319.1
Copyright (c) Microsoft Corporation. All rights reserved.

corflags : warning CF011 : The specified file is strong name signed. Using /For
ce will invalidate the signature of this image and will require the assembly to
be resigned.

Lets double check it worked:

 
C:\Program Files (x86)\Microsoft F#\v4.0>corflags fsi.exe
Microsoft (R) .NET Framework CorFlags Conversion Tool. Version 4.0.30319.1
Copyright (c) Microsoft Corporation. All rights reserved.

Version : v4.0.30319
CLR Header: 2.5
PE : PE32
CorFlags : 9
ILONLY : 1
32BIT : 0
Signed : 1

Finally fire up F#, and it's now in 64 bit - yippee!