The ever charismatic Mr. Box made a lovely post about continuations in C# 2.0:

<?xml:namespace prefix = o ns = “urn:schemas-microsoft-com:office:office” /> /o:p

Because I have used a simpler Fibonacci implementation in couple of places, I thought I’d port it to F#.


Of course continuations are not a new idea; they have been used for a long time in ML style programming. The implementation is most like the continuations by anonymous methods, as anonymous methods work well in ML as they are very similar idea to lambdas.


Here is the source:



let fib() = /o:p

      let i = ref 0 in /o:p

      let j = ref 1 in/o:p

      let cont() = (/o:p

                let result = !i in/o:p

            i := !j;/o:p

            j := result + !j;/o:p


            ) in/o:p



let _ = let x = ref 0 in/o:p

      let f = fib() in/o:p

      while !x < 1000 do/o:p

            x := f();/o:p

            Printf.printf “%d\n” !x;/o:p