The end result is that we have turned recursion into

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: begin match no with! | None -> 0! | Some n -> 1 + (loop n.next)! end! 39 Evalua@ng length Workspace Stack length 2! q Heap fun (q:'a queue) ->! let rec loop (no:…) : int =! …! in! loop q.head ! head! tail! v! DONE! 1! next! v! next! 2! None! fun (no: …) ->! begin match no with! | None -> 0! | Some n -> 1 + (loop n.next)! end! CIS120 / Spring 2012 40 Itera@on loops length (using itera@on) (* Calculate the length of the list using iteration *)! let length (q:'a queue) : int =! let rec loop (no:'a qnode option) (len:int) : int =! begin match no with! | None -> len! | Some n -> loop n.next (1+len)! end! in! loop q.head 0! •  This code for length also uses a helper func@on, loop: –  This loop takes an extra argument, len, called the accumulator –  Unlike the previous solu@on, the computa@on happens “on the way down” as opposed to “on the way back up” –  Note that loop will always be called in an...
View Full Document

This document was uploaded on 11/24/2013.

Ask a homework question - tutors are online