Functional programming is becoming more and more mainstream these days. C# 3.0, Python & Ruby have embodied many of the functional approaches. Microsoft even is releasing F# as first class language in Visual Studio 2010. F# is complaint in syntax with OCaml. Back in the day (at UC Santa Cruz) I wrote a language translator using OCaml and loved the symbolic computation capability a functional language provides.
In this version of interesting programming concepts, I would like to highlight type system based pattern matching available in F#/OCAML, its very unique and extremely useful if you are parsing a structured list or working on a symbol table:
type Expr = | Num of int | Add of Expr * Expr | Mul of Expr * Expr | Var of string let rec Evaluate (env:Map<string,int>) exp = match exp with | Num n -> n | Add (x,y) -> Evaluate env x + Evaluate env y | Mul (x,y) -> Evaluate env x * Evaluate env y | Var id -> env.[id]
In fact listed below is most of the code for code-generator main loop from my tool translating Berkeley Logic Interchange format (BLIF) to Reactive Modules :
let emit_atoms() = let vemit_atom a b = begin match b with Symb(Input,_,None) -> () | Symb(_,_,None) -> emit_unmarked_atom a | Symb(_,_,TableAtom (Controls(p),Awaits(q),Relations(r))) -> begin emit_atom_start (); emit_table_io_stmts p q; emit_init_update (); emit_relations p q r; emit_atom_end (); end | Symb(_,_,ResetAtom (Controls(p),Awaits(q),Relations(r))) -> begin emit_atom_start (); emit_reset_io_stmts p q; emit_init_update (); emit_relations p q r; emit_atom_end (); end ... | Symb(_,_,SameAs(t)) -> () | _ -> raise (Failure("Unknown Error")) end in Hashtbl.iter vemit_atom symTab;
In closing, I would like to show how one can use C# select as an equivalent to map in functional languages.
// Get elements in the store where filenames are GUIDs public IEnumerable<Guid> GetKeys() { string[] files = Directory.GetFiles(_StorePath); // functional equivalent: return files.map(|t| new Guid(t)) return (files.Select( p => new Guid( Path.GetFileName(p)))); }
Feel free to share your bits and pieces of functional goodness in the comments below!

3 comments ↓
[...] Viabhav Bhandari’s F# – Functional Approach [...]
[...] Viabhav Bhandari’s F# – Functional Approach [...]
[...] Techniques & Data Analysis Functional Programming, Memoization .. ring a bell? Well I plan on dwelling more on programming techniques and data [...]
Leave a Comment