Saturday, December 24, 2011

F# Grouping Pattern



As the pattern matches contain more and more rules, you might want to combine patterns. There are two ways to combine patterns. First is to use OR represented by a
vertical pipe | , which combines patterns together so the rule will fire if any of the grouped patterns match. Second is to use AND represented by an ampersand &, which combines patterns together so that the rule will fire only if all of the grouped patterns match.

let vowelTest c =
match c with
|'a'|'e'|'i'|'o'|'u'
-> true
-> false
|_

let describeNumbers x y =
match x,y with
| 1, _
| _, 1
-> "One of the numbers is one."
| (2,_) & (_,2)
-> "Both of the numbers is two."
-> "Other."


AND pattern has litte use in normal pattern matching, however itz invaluable when using active patterns.

Sunday, December 18, 2011

F# Pattern Matching


Pattern matching is logically similar to a switch statement in C#, Java, C++, etc; but itz much more powerful. A pattern match is a series of rules that will execute if the pattern matches the input. The pattern match expression then returns the result of the rule that was matched. So, all rules in a pattern match must return the same type.

In F#, you use match and with keywords with a series of pattern rules, followed by an arrow -> for pattern matching. Herez a sample F# pattern match code for Odd validation.


> let isOdd x = (x % 2 = 1)
let describeNumber x =
match isOdd x with
| true -> printfn “number is odd”
| false -> printfn “ number is even”;;

> describeNumber 4;;
number is even
val it : unit = ()


Truth Table
Letz take AND truth table example using type inference on pattern matches. Herez the code:


> let testAND x y =
match x, y with
| true, true -> true
| true, false -> false
| false, true -> false
| false, false -> true
> testAND true false;;
val it: bool = true


Match Failure
If no match is found during a pattern matching, an exception of type Microsoft.Fsharp.Core.MatchFailureException is raised. You can avoid this by making sure that all possible cases are coverd. Fortunately, F# compiler will issue a warning when it can determine that pattern match rules are incomplete.


> let testAND x y =
match x, y with
| true, true -> true
// Commented | true, false -> false
| false, true -> false
| false, false -> true
> testAND true false;;

Microsoft.Fsharp.Core.MatchFailureExcption: The match cases were incomplete at:....
Stopped due to error


Pattern matching rules are checked in the order they are declared.

Sunday, December 11, 2011

F# Symbolic Operator


Letz think of writing add 1 2 in the declarative way in stead of traditional way 1+2 everytime. Itz called as a symbolic operator. F# has not only built-in symbolic operators but also custom defined own symbolic operators. It helps the developers to write code in a cleaner and elegant way. In fact symbolic functions are not as form of operator overloading; rather functions whose names
are made out of symbols.

A symbolic operator can be made up of any sequence!@#$%^&*+-/<=>~| symbols. Herez the code defines a new function ! that computes the factorial of a given number

> let rec(!) x =
if x <= 1 then 1
else x * !(x-1);;

> !5;;
val it : int = 120

To have symbolic operators that come before their parameters are known as prefix notation. You must prefix the function with a tilde ~, exclamation point ! or question mark ? operator. In the below code, the function ~++ is prefixed with a tilde and thus to call it, you write ~++ 1 2 3 rather than 1 ~++ 2 3. This enables you to use symbolic operators that more naturally fit the style of function being defined as:

> let (~++) x y z = x + y + z;;

val (~++) : int-> int-> int-> int

> ~++ 1 2 3;;
val it : int = 6

In addition to allowing you to name functions that map more closely to mathematics, symbolic operators can also be passed around to higher order functions if you simply put parentheses around the symbol.

Sunday, December 4, 2011

F# List


Last week Tuples group values into a single entity. List allows you link data together to form a chain. F# define a list as ; delimited values enclosed in brackets as:


let countDown = [9;8;7;6;5;4;3;2;1];;

F# has only two operations. They are (i) cons :: operator, to add an element in front of list (ii) append @ operator, to add at the last. Examples are:
>let countDown = 10::countDown;;

val countDown : int list = [10;9;8;7;6;5;4;3;2;1]

>let countDown = 0@countDown;;

val countDown : int list = [10;9;8;7;6;5;4;3;2;1;0]

List Range

To declare a list of ordered numeric values, List range specifies the lower and upper range as:
>let counter = [1..10];;

val counter : int list = [1;2;3;4;5;6;7;8;9;10]

List comprehension

Itz a rich syntax that allows you to generate list inline with F# code. The body of the list comprehension will execute until it terminates, and the list will be made up of elements returned via yield keyword.
let numbersNear x =
[
yield x-1
yield x
yield x+1
];;

List.map

List.map function creates a new collection by applying a function to the given collection. Just have a look on attached image example

When you print r1 the example, you should get the output as 2,3,4,5

List.Iter

It iterates thro each element of the list and calls a funtion that you pass as a parameter.

Tuesday, November 29, 2011

F# Core Types


Besides the primitive types, the F# library includes several core types that will allow you to organize, manipulate and process data

Unit
The unit type is a value signifying nothing of consequence. unit can be thought of as a concrete representation of void and is represented in code via ():


> let x=();;

val x : unit=()

> x;;
val it : unit()

if expres­sions without a matching else must return unit because if they did return a value, what would happen if else was hit?

Also, in F#, every function must return a value, think method in C# and the void return type, so even if the function doesn’t conceptually return any­thing then it should return a unit value.

The ignore function can swallow a function’s return value if you want to return unit:

> let square x=x*x;;

val square :int->int

> ignore (square 3);;
val it : unit=()


Tuple
A tuple (pronounced two-pull) is an ordered collection of data,easy way to
group common pieces of data together. For example, tuples can be used to track
the intermediate results of a computation.

To create an instance of a tuple, separate group of values with comma, and optionally
place them within parentheses. Letz have fullName as an instance of a tuple, while
string * string is the tuples type:

> let fullName = ("ganesan", "senthilvel");;
val fullName : string * string = ("ganesan", "senthilvel")

Tuples can contain any number of values of any type. You can have a tuple that
contains other tuples.

Friday, November 25, 2011

TechMela


Last week, itz completely packed with technical conferences. To start with, Amazon had Amazon Web Services (AWS) Cloud tour at Chennai on Tuesday 15 Nov. Amazon CTO Dr. Werner Vogels was the chief guest for the conference with impressive key note address. He talked about cloud computation via Hadoop, MapReduce and storage via NoSQL. We had discussion panel with 4 CTOs who are prime customers for AWS Cloud. On Thursday 17 Nov, our firm had architecture summit 2011 and our CTO addressed about governance, life cycle management, listening to the customers and shared services. On Friday 18 Nov, Microsoft had their web camp with key note address by Gianugo Rabellino, product manager from Seattle. Sessions were around HTML5, CSS3, Webmatrix and Razor with hands on demo.

On Saturday Nov, took part in ThoughtWorks bar camp at their Chennai office. I heard about the work culture of the firm and their innovation on Agile development; but literally thrilled on seeing their work environment. It needs lot of maturity among their developers community. Miles to go! Back to the tech mela. Presented a session on Cloud computing using Azure between 10:30-11:15 am with few tech geeks. Had few hands on demo and fighting debates. Really loved it. Attended other sessions on Thrift, Scala, Coffeescript, Rails and open source impact. Itz pack jam of technical stuff through out the week and so named as TechMela.

Lessons learnt from TechMela:
  • Map reduce for the independent high CPU intensive threads
  • Evolution of Amazon and itz cloud entry as pioneer for their internal need
  • AWS storage trend using NoSQL model
  • Building shared services along with the development
  • Life cycle management impact on architecture
  • Vital role of governance in end to end architecture
  • Emerging technology role by HTML5 and itz impact on RIA vendors like Microsoft, Adobe
  • Role of functional programming (like scala, F#) to build complex app
  • New frameworks like Thrift, Rails
  • Awesome environment to present my cloud paper

Of course, had great opportunity to connect tech giants (CTOs, local tech geeks). Happy thanks giving week end, folks! Will continue our F# journey...


Saturday, November 19, 2011

F# Function


Function Definition
F# function is defined as values, except everything after the name of the function serves as parameters. Herez incrementor function


> let incrementer x = x+1;;

val incrementer : int->int

> incrementer 6;;
val it:int=7


Unlike C#, F# has no return keyword; it returns the last evaluted expression.

Type Inference
F# is statically typed, calling incrementer function with floating value will result in a compilation error as:

> incrementer 6.0;;

error FS0001: This expression has type float


Reason is becaz of type inference, which requires explicitly state of the types. Type inference is different from dynamic typing. Though, F# allows to omit types, it doesn't mean that type checking is not enforced at compile time.

Generic Function
Type of generic parameter can have the name of any valid identifier prefixed with an apostrophe. Below code defines incrementer function using a type annotation that forces the parameter x to be generic.

> let incrementer (x:'a) = x+1;;

val incrementer : 'a->'a


Writing generic code is important for maximizing code reuse. In this example, parameter 'a can be an int, float, string, user defined type, etc.