F# Basics Part 2

Lightweight Syntax

F# provides the compiler directive #light which simplifies the language and lets the programmer worry less about syntax. The #light directive is a signal to the compiler to loosen up some of its syntactic rules and use the indentation of the code instead. For instance, the two functions below are functionally equivalent but the second uses the lightweight syntax.

let addingNumbers x y =   let number1 = x in
                                            let number2 = y in
                                            number1 + number2
#light
let addingNumbersWithLight x y =
    let number1 = x
    let number2 = y
    number1 + number2
 

Notice that the second function does not need the in keyword. The compiler is able to determine the programmer’s intent by using the indentation of the code (more about in and scope to come). When indenting your code using lightweight syntax try and use 4 or 5 spaces. YOU CANNOT USE TABS. And of course, if the lines aren’t spaced probably your code will not compile. For instance, the following code will NOT compile:

#light
    let addingNumbersWithLight x y =
       let number1 = x
    let number2 = y
    x + 1

Overall, lightweight syntax is pretty cool because it allows the developer to worry more about what’s important and less about the repetitive syntactic tokens. Going forward, most of the examples you see on this site will assume the use of the #light directive.

Comments in F#

You can comment your code in F# a couple of ways. The first is using the classic // to comment out a particular line. Here’s an example:

 //let commentedFunction x = x + 1

You can comment out multiple lines of code using (*…*)  like this :

(* let commentedFunction x =  let x = 1
                                                    let y = x + 1 *)

You can also leverage the XmlDocument features of the .Net framework using ///.  Here’s an example of that:

///<summary>
///cubed takes an integer and returns the integer cubed
///</summary>
///<returns>
///The function returns the integer cubed
///</returns>
let cubed x = x * x * x    

Comments
New Zealand  8/19/2008

Very Nice Site! Thanx! http://excellent-credit-card.blogspot.com
Alachua, Florida  8/30/2008

Where did your cool forums go? they were an integral part of this excellent site.
  10/16/2008

NikkyBlond  11/5/2008

Enjoyed your site very much! Thank you! Keep up a good work! :-))
Leave Us a Comment!
Title (we need it)

Your Name (we need it)

Your Comment (we need it)