Tuesday, December 10, 2013

F# Functions

Functions (F#) @ MSDN

F# is a hybrid functional language, that supports object-oriented (.NET) and functional concepts. It has very compact syntax.
It is so compact that commas and brackets are not used! It takes some time to get used to...
Here are some C# method declarations:
int add(int x, int y) { return x+y; }
string add(string x, string y) { return x+y; }
Here is equivalent function declaration in F#; F# is strongly typed, and compiler can assign data type of function and arguments based on context! In example below, "add 3 5" will produce value 8 of type int; the next line that is commented out would produce a string; so same declaration can be for int and string, but not at the same time, since compiler decides type based on first occurrence.
let add x y = x + y

printfn "%d" (add 3 5)
// printfn "%s" (add "Hello" "World")
F# functions are just values, and can be assigned and passed around as parameters; For example add'  gets assigned a lambda expression (anonymous function), with same meaning as previous declaration:
let add' = fun x y -> x + y
function can have data types declared:
let add (x: int) (y:int) : int =
    x + y

The compiler can also infer function type of parameter from context;
in example below "checkThis" is function declaration that takes two parameters "item" and "f";
f is recognized to be a function parameter, since in "if" statement it is taking item as argument
When calling "checkThis" , lambda expression is used as a value for "f"
let checkThis item f =
    if f item then
        printfn "HIT"
    else
        printfn "MISS"

checkThis 5 (fun x -> x > 3)
checkThis "hi there" (fun x -> x.Length > 5)



No comments: