Skip navigation

Coming from imperative paradigm, I have to admin I rarely use recursion in my code design. Because it is very natural way to use loop or to encapsulate the business logic in "Iterator" (even one of the patterns from GOF).

But in functional language, like F#, it is very natural to design application using recursion, which make the code more concise, succinct and expressive. It tells “What”, instead of “How”.

Let’s take a simple Factorial function as an example to explain how recursion works.

let rec factorial n =
     if n = 0 then 1
     else
        n * factorial (n -1)


The function looks simple, which is exactly the same way as its mathematical expression.

But if we provide a very large number such as 1,000,000, it might raise StackOverFlow exception, because the compiler use stack to store the functions. The stack space is very precious, only 1 M. It sounds like the recursion is not applicable for processing large data. Fortunately, F# compiler can optimize recursion by applying “Tail Recursion”.

“Tail Recursion” is a special recursive function which does not including any other execution after the recursive call, meaning there is no “pending operation”

Obviously, the factorial function above is not “Tail Recursion” because it has to multiply n. How do we solve it? A common approach is to use accumulator pattern. Here is the code:

let rec factorialTR n a =
    if n = 0 then a
    else
       factorialTR (n - 1) (n * a)

The idea is, instead of accumulating the functions in the stack, the code use a “accumulator” type to get the temporal value, which is (n * a) in the function. When it function reaches its base, it only needs to return the “accumulator” value. You see, in this case, compiler does not need to store additional additional functions in the stack any more. Makes sense, right?

Is Factorial function too simple? OK, let’s take some “real world” samples.

1. Sum a List (Just be aware the the list in F# is linked list)

let tempList = [1 .. 1000000]

// Non Tail Recursion Version
let rec sumList lst =
    match lst with
    | [] -> 0
    | hd :: tl -> hd + sumList tl 

sumList tempList

// Tail recursion version
let sumListTR list  =
    let rec innerSum list total =
         match list with
         | [] -> 0 // initial value
         | hd :: tl ->
            let ntotal = hd + total
            innerSum tl ntotal // don't need to store in stack
    innerSum list 0

The first one is not “Tail Recursion” because the recursion function is not the “last” thing, it has to append the value with hd.

The second one is “Tail Recursion” since it calculates the “AsOf” value and the temporal value is one of the parameter passed in the function. There is nothing needed to be stored in the stack.

2. Map function (Note: Map is one of high order functions common in Functional Language)

// Non-Tail Recursive version map  function
let rec map f list =
    match list with
    | [] -> []
    | hd :: tl -> (f hd) :: (map f tl)

// Tail Recursion Version


let mapTR f list =
    let rec loop f list acc =
        match list with
        | [] -> acc
        | hd :: tl -> loop f tl (f hd :: acc) 

     loop f (List.rev list) []

“Tail Recursion” makes it a very useful in our tool box. But it might reach its own limitation that “Tail Recursion” is allow one recursion call in a function. If there have more, we cannot covert it to “Tail Recursion”, so we cannot take the optimization offered by F# compiler.

Take a sample when we process a Tree:

type Tree<'a> =
  | Node of 'a * Tree<'a> * Tree<'a>
  | Leaf of 'a

// Non Trail Recursion version
let rec treeSize = function
  | Leaf _ -> 1
  | Node(_, left, right) -> treeSize  left + treeSize  right

// Trail Recursion version
let  treeSizeTR tree =
  let rec size_acc tree acc =
    match tree with
    | Leaf _ -> 1 + acc
    | Node(_, left, right) ->
        let acc = size_acc left acc // Non Tail Recursion on left
        size_acc right acc          // Tail Recursion on right
  size_acc tree 0

You can see we provide two version of codes to process a tree. The first one is a normal approach by calling two recursive functions. It is interesting to see the second one. As you can see we only have one “Tail Recursion” when processing right side tree. So the whole solution still cannot be optimized by F# compiler.  Now what we should do?

Let’s think about how we apply “accumulator” pattern to solve “Trail Recursion” issue again. We pass a temporal value as an argument to the function. Just be ware, in functional language like F#, function is value too. It can be passed and returned! It is a fundamental in functional programming, but it can help us to solve very tricky issue. OK, let me tell you the answer first, then explain.

The answer is to applying continuous passing style (CPS) by passing another function as the “remaining” of the recursive function call.  So what does it mean? Still confused? Well, actually it is really confusing. It is not very easy to understand when you see it first time. Still, let’s use Fibonacci function we used in the early to illustrate how continuations works.

let  fibonacciCPS n =
  let rec fibonacci_cont a cont =
    if a <= 2 then cont 1
    else
      fibonacci_cont (a - 2) (fun x ->
        fibonacci_cont (a - 1) (fun y ->
          cont(x + y)))

  fibonacci_cont n (fun x -> x)

This implementation takes a inner recursive function by passing the number and a continuation function. Actually the continuation function is a  closure function.

1. when a <=2, it returns by applying the identifier function (fun x –> x)

2. When a > 2, it recursively calls to reach its base case by calling fibonacci_cont (a – 2), and in the same time, it builds up the closure functions. x is the result of fibonacci_cont (a –  2), and y is the result of fibonacci_cont (a –1). The add x and y.

3. Just be aware we use closure here, which use heap, instead of stack.

It really makes the logic inside out. It does not seem a very natural way when we design the code. It made my head hurt when first seeing this code. But later, I think it is very smart to pass closure function like that. It is really the beautiful side of functional programming.

Well, this blog might be too length. I will continue discussing recursive function later. Now let me finish this blog by putting the code to process a tress using continuation at the end.

let  treeSizeCont tree =
  let rec size_acc tree acc cont =
    match tree with
    | Leaf _ -> cont (1 + acc)
    | Node(_, left, right) ->
        size_acc left acc (fun left_size ->
          size_acc right left_size cont)

  size_acc tree 0 (fun x -> x)

 

Happy programming!

KeyboardOne the of the tips I heard to become a productive developer is to use mouse as few as possible, put the fingers on the keyboard.

Mouse clicking is sort of distraction from we are doing. Combining with any of the launcher tool, such as Slickrun, you will find you can definitely accomplish your work faster, more effectively and a lot fun!

Don’t try to memorize all of them at once. When you feel you need to use mouse, just do some search to see if any shortcut available. Here is the list I am using a lot as a .NET developer (visual studio and Resharper, of course!)

Here are some of the window-based shortcuts I collected and use very often. Hope it will help.

Visual Studio Shortcut Keys

Shortcut Keys Description
Ctrl + X Cut the current selected item to clipboard
Ctrl + C Copies the current selected item to the clipboard
Ctrl + V Pastes the item in the clipboard at the cursor
Ctrl + Z Undo previous editing action
Ctrl + Y Redo the previous undo action
Esc Closes a menu or dialog, cancels an operation in progress, or places focus in the current document window
Ctrl + S Saves the selected files in the current project (usually the file that is being edited)
Ctrl + Shift + S Saves all documents and projects
Shift + F12 Finds a reference to the selected item or the item under the cursor
Ctrl + End Moves the cursor to the end of the document
Ctrl + Home Moves the cursor to the start of the document
Ctrl + G Displays the Go to Line dialog
Ctrl + Right Arrow Moves the cursor one word to the right
Ctrl + Left Arrow Moves the cursor one word to the left
Ctrl + K, Ctrl + C Marks the current line or selected lines of code as a comment
Ctrl + K, Ctrl + U Removes the comment syntax from the current line or currently selected lines of code
Ctl + J Lists members for statement completion when editing code
Ctrl + R, Ctrl + W Shows or hides spaces and tab marks
Shift-Left Arrow Moves the cursor to the left one character, extending the selection
Ctrl + Shift + End Moves the cursor to the end of the document, extending the selection
Ctrl + Shift + Home Moves the cursor to the start of the document, extending the selection
Shift + Down Arrow Moves the cursor down one line, extending the selection
Shift + End Moves the cursor to the end of the current line, extending the selection
Shift + Home Moves the cursor to the start of the line, extending the selection
Shift + Up Arrow Moves the cursor up one line, extending the selection
Shift + Page Down Extends selection down one page
Shift + Page Up Extends selection up one page
Ctrl + A Selects everything in the current document
Ctrl + Shift + Page Down Moves the cursor to the last line in view, extending the selection
Ctrl + Shift + Page Up Moves the cursor to the top of the current window,
Ctrl + Shift + Alt + Right Arrow Moves the cursor to the right one word, extending the column selection
Ctrl + Shift + Left + Arrow Moves the cursor one word to the left, extending the selection
Ctrl + Shift + B Build the solution
Ctrl + Shift + N Display the New Project dialog
Ctrl + O Display open the file dialog
Ctrl + Shift + O Display open project dialog
Shift + Alt + A Display the Add Existing Item dialog
Ctrl + Shift + A Display the Add New Item dialog
Shift + Alt + Enter Toggles full screen mode
Ctrl + Tab Cycles through the MDI child windows one by one
Ctrl + F Display the Find dialog
Ctrl + Shift + F Display the Find in Files dialog
F3 Find Next
Ctrl + H Display the Replace dialog
Ctrl + Shift + H Display the Replace in Files dialog


Basic Windows shortcut keys

Shortcut Keys Description
Alt+F File menu options in current program.
Alt+E Edit options in current program
F1 Universal Help in almost every Windows program.
Ctrl+A Select all text.
Ctrl+X Cut selected item.
Shift+Del Cut selected item.
Ctrl+C Copy selected item.
Ctrl+Ins Copy selected item
Ctrl+V Paste
Shift+Ins Paste
Home Goes to beginning of current line.
Ctrl+Home Goes to beginning of document.
End Goes to end of current line.
Ctrl+End Goes to end of document.
Shift+Home Highlights from current position to beginning of line.
Shift+End Highlights from current position to end of line.
Ctrl+Left arrow Moves one word to the left at a time.
Ctrl+Right arrow Moves one word to the right at a time.
Alt+Tab Switch between open applications.
Alt+Shift+Tab Switch backwards between open applications.
Alt+double-click Display the properties of the object you double-click on.
Ctrl+Tab Switches between program groups or document windows in applications
Ctrl+Shift+Tab Same as above but backwards.
Alt+Print Screen Create a screen shot only for the program you are currently in.
Ctrl+Alt+Del Reboot the computer and/or bring up the Windows task manager.
Ctrl+Esc Bring up the Windows Start menu.
Alt+Esc Switch Between open applications on taskbar.
Alt+F4 Closes Current open program.
Ctrl+F4 Closes Window in Program.
Shift + Del Delete programs/files without throwing them into the recycle bin.
Holding Shift Boot Safe Mode or by pass system files as the computer is booting
Holding Shift When putting in an audio CD, will prevent CD Player from playing.
Ctrl+F9 Minimize current window.
Ctrl+F10 Maximize currently selected window.
Windows Logo Start menu
Windows Logo+R Run dialog box
Windows Logo+M Minimize all
SHIFT+Windows Logo+M Undo minimize all
Windows Logo+F1 Help
Windows Logo+E Windows Explorer
Windows Logo+F Find files or folders
Windows Logo+D Minimizes all open windows and displays the desktop
CTRL+Windows Logo+F Find computer
CTRL+Windows Logo+TAB Moves focus from Start, to the Quick Launch toolbar, to the system tray
Windows Logo+TAB Cycle through taskbar buttons
Windows Logo+Break System Properties dialog box
Windows Logo+L Log off Windows
Windows Logo+P Starts Print Manager
Windows Logo+C Opens Control Panel
Windows Logo+V Starts Clipboard
Windows Logo+R Open and Run Window


Web Browser common shortcut Keys

Shortcut Key Description
Ctrl + N Open a new window
Ctrl + T Open a new tab
Ctrl + W Close the current window
Ctrl + R Refresh
Esc Stop
Alt + <- Back
Alt + -> Forward
Alt + Home Go to your homepage
Alt + D Move focus to the address bar to type URL
Ctrl + Enter Add “http://www.” and “.com” around an address


Mozilla Firefox shortcut Keys

Shortcut Keys Description
Alt + Home Home
Alt + Left Arrow Back a page.
Backspace Back a page.
Alt + Right Arrow Forward a page.
F5 Refresh current page, frame, or tab.
F11 Display the current website in full screen mode. Pressing F11 again will exit this mode.
F3 Find Again
Esc Stop page or download from loading.
Ctrl + (- or +) Increase or decrease the font size, pressing ‘-’ will decrease and ‘+’ will increase.
Ctrl + Enter Quickly complete an address. For example, type computerhope in the address bar and press CTRL + ENTER to get http://www.computerhope.com
Shift + Enter Complete a .net instead of a .com address.
Ctrl + Shift + Enter Complete a .org address.
Ctrl + Shift + Del Open the Clear Data window to quickly clear private data.
Ctrl + W Close the current window or tab
Ctrl + D Add a bookmark for the page currentlys opened.
Ctrl + I Display available bookmarks.
Ctrl + J Display the download window.
Ctrl + N Open New browser window.
Ctrl + P Print current page / frame.
Ctrl + T Opens a new tab.
Ctrl + F4 Closes the currently selected tab.
Ctrl + Shift + T Undo the close of a window.
Ctrl + Tab Moves through each of the open tabs.
Ctrl + Shift + Tab Swich to the previous tab
Ctrl + G Find the previous occurrence of a search phrase
Ctrl + K Move cursor to the Web Search Widget (top right of the screen)
Spacebar Moves down a page at a time.
Shift + Spacebar Moves up a page at a time.
Alt + Down arrow Display all previous text entered in a text box and/or available options on drop down menu.


Internet Explorer Shortcut

Shortcut Keys Description
Alt + Left Arrow Back a page
Backspace Back a page
Alt + Right Arrow Forward a page.
F5 Refresh current page, frame, or tab.
F11 Display the current website in full screen mode
Esc Stop page or download from loading.
Ctrl + (- or +) Increase or decrease the font size, pressing ‘-’ will decrease and ‘+’ will increase.
Ctrl + Enter Quickly complete an address. For example, type computerhope in the address bar and press CTRL + ENTER to get http://www.computerhope.com.
Ctrl + D Add a Favorite for the page currently opened.
Ctrl + I Display available bookmarks.
Ctrl + N Open New browser window.
Ctrl + P Print current page / frame.
Ctrl + T Opens a new tab.
Ctrl + F4 Closes the currently selected tab.
Ctrl + Tab Moves through each of the open tabs.
Spacebar Moves down a page at a time.
Shift + Spacebar Moves up a page at a time.
Alt + Down arrow Display all previous text entered in a text box and/or available options on drop down menu.

Microsoft Excel

Shortcut Keys Description
F2 Edit the selected cell.
F5 Goto a specific cell. For example, C6.
F7 Spell check selected text and/or document.
F11 Create chart.
Ctrl + Shift + ; Enter the current time.
Ctrl + ; Enter the current date.
Alt + Shift + F1 Insert New Worksheet.
Shift + F3 Open the Excel formula window.
Shift + F5 Bring up search box.
Ctrl + A Select all contents of the worksheet.
Ctrl + B Bold highlighted selection.
Ctrl + I Italic highlighted selection.
Ctrl + K Insert link.
Ctrl + U Underline highlighted selection.
Ctrl + 5 Strikethrough highlighted selection.
Ctrl + P Bring up the print dialog box to begin printing.
Ctrl + Z Undo last action.
Ctrl + F6 Switch between open workbooks / windows.
Ctrl + Page up Move between Excel work sheets in the same Excel document.
Ctrl + Page down Move between Excel work sheets in the same Excel document.
Ctrl + Tab Move between Two or more open Excel files.
Alt + = Create a formula to sum all of the above cells
Ctrl + ‘ Insert the value of the above cell into cell currently selected.
Ctrl + Shift + ! Format number in comma format.
Ctrl + Shift + $ Format number in currency format.
Ctrl + Shift + # Format number in date format.
Ctrl + Shift + % Format number in percentage format.
Ctrl + Shift + ^ Format number in scientific format.
Ctrl + Shift + @ Format number in time format.
Ctrl + Arrow key Move to next section of text.
Ctrl + Space Select entire column.
Shift + Space Select entire row.

Microsoft Word

Shortcut Keys Description
Ctrl + A Select all contents of the page.
Ctrl + B Bold highlighted selection.
Ctrl + C Copy selected text.
Ctrl + X Cut selected text.
Ctrl + P Open the print window.
Ctrl + F Open find box.
Ctrl + I Italic highlighted selection.
Ctrl + K Insert link.
Ctrl + U Underline highlighted selection.
Ctrl + V Paste.
Ctrl + Y Redo the last action performed.
Ctrl + Z Undo last action.

I had a lot of fun to read Tomas Petricek’s article, "Concepts behind the C# 3.0 language". Instead of listing all of the new syntax changes as most of other tutorials, Tomas shed some lights on the details about influence of the development of C# 3.0 from other languages, especially how Functional programming plays in C# 3.0. Actually, Lambda Expression and LINQ are really part of that.

So what is functional programming? Quote from Wikipedia:

"Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast with the imperative programming style that emphasizes changes in state.[1] "

So what it really tells us? I think the main point is "function is data" which means function can be use to be passed as an parameter or returned argument or modified as any other data in our application. Do we gain benefit for that? Sure, we do.

1. Functional programming can help model data operation. Here is the sample:

1 private static long Watch<T>(Action<T> act, T arg) 2 { 3 Stopwatch watch = new Stopwatch(); 4 watch.Start(); 5 act(arg); 6 watch.Stop(); 7 return watch.ElapsedMilliseconds; 8 }

This Watch function is totally decoupled with the Action, which could be "reading the data from database", or "processing the data from a file". It leads a clean design that Watch function and the Action function can be tested separately.

2. Parallel programming. If you have been worked on Multi-thread programming. You know how hard it is. The limitation of imperative language like C# focuses on the state change. But functional programming is passing function as argument as we mentioned above. The state actually is only closed in the function boundary. So there is no other thread can access that data. Microsoft has released PLINQ, a parallel programming add-on to current .NET framework 3.5. It will be a huge benefit for any .NET who will take advantage of multi-processor computers.

So far, so good, right? from next one, I will illustrate the functional programming features in C# 3.0. Definitely will show more code. Please stay tune.

My previous blog is about using DTO in UI/Presenter layers. Just studying Nhibernate source code now, I find a very interesting approach to populate DTO object directly from Nhibernate with Criteria and Projections.
Here is the code:

   1:  IList resultWithAliasedBean = s.CreateCriteria(typeof(Enrolment))
   2:   .CreateAlias("Student", "st")
   3:   .CreateAlias("Course", "co")
   4:   .SetProjection(Projections.ProjectionList()
   5:   .Add(Projections.Property("st.Name"), "studentName")
   6:   .Add(Projections.Property("co.Description"), "courseDescription")
   7:  )
   8:  .AddOrder(Order.Desc("studentName"))
   9:  .SetResultTransformer(NHibernate.Transform.Transformers
  10.  .AliasToBean(typeof(StudentDTO)))
  11:  .List();

The Element and StudentDTO is simple enough.

   1:          [Serializable]
   2:      public class Enrolment
   3:  
   4:          private Student student;
   5:          public virtual Student Student
   6:          {
   7:              get { return student; }
   8:              set { student = value; }
   9:          }
  10:  
  11:          private Course course;
  12:          public virtual Course Course
  13:          {
  14:              get { return course; }
  15:              set { course = value; }
  16:          }
  17:  
  18:          private long studentNumber;
  19:          public virtual long StudentNumber
  20:          {
  21:              get { return studentNumber; }
  22:              set { studentNumber = value; }
  23:          }
  24:  
  25:          private string courseCode = string.Empty;
  26:          public virtual string CourseCode
  27:          {
  28:              get { return courseCode; }
  29:              set { courseCode = value; }
  30:          }
  31:  
  32:          private short year;
  33:          public virtual short Year
  34:          {
  35:              get { return year; }
  36:              set { year = value; }
  37:          }
  38:  
  39:          private short semester;
  40:          public virtual short Semester
  41:          {
  42:              get { return semester; }
  43:              set { semester = value; }
  44:          }
  45:  
  46:          public override bool Equals(object obj)
  47:          {
  48:              Enrolment that = obj as Enrolment;
  49:              if (that == null)
  50:                  return false;
  51:              return studentNumber == that.StudentNumber && courseCode.Equals(that.CourseCode);
  52:          }
  53:  
  54:          public override int GetHashCode()
  55:          {
  56:              return courseCode.GetHashCode();
  57:          }
  58:      }
  59:  public class StudentDTO
  60:      {
  61:          private string studentName;
  62:          private string courseDescription;
  63:  
  64:          public StudentDTO() { }
  65:  
  66:          public string Name
  67:          {
  68:              get { return studentName; }
  69:          }
  70:  
  71:          public string Description
  72:          {
  73:              get { return courseDescription; }
  74:          }
  75:      }

What we can do is to retrieve StudentDTO from Presenter by querying from Repository. Code is elegant and beautiful. How sexy NHibernate is!!

DTO (Data Transfer Object)is a very common used pattern in enterprise applications. Martin Fowler also documented it in his class book “Pattern Enterprise Application Architecture“. In the meanwhile, DTO is also a very famous “Anti-Pattern”. The pure OO purist think DTO is a devil. It is so easy to build. The object become nothing but a simple data container, which represent the data in the tables instead of the real domain objects. The business logic embedded in the application is going to shift from middle domain logic tier to tables, most of time spreaded among the stored procedures, which is leading to a unmaintainable solution.

So should we give up DTO totally in our application design? Absolutely not, in the other end, I find DTO still useful especially in UI and UI process layers. For example, we have a complex searching page to find customer by first name, last name, SSN, address, phone, email, and so on. those information may stay in different domain objects. It is also very hard to design a method with a very long list of parameters, not just ugly but also unmaintainable. My approach is to design DTO object pass data between UI and UI process (Presenter or Controller). Then access the service objects, and domain objects from presenter/controller. So I can design domain entity with the interfere from the special requirement of UI. Again it is important to implement MVP pattern to protect the domain object, which is also one of the important principles I heard from DDD: don’t leak business logic out of the domain object layer.

Follow

Get every new post delivered to your Inbox.