about recursive looping

Discussion in 'Mac Programming' started by Sydde, Apr 29, 2013.

  1. Sydde macrumors 68020


    Aug 17, 2009
    I was casually reading through a long tutorial on one of those odd functional languages (Haskell) and got to wondering about the recursion thing. Obviously, recursive loops in a procedural language look kind of elegant but could present something of a risk if compiled verbatim (an arbitrarily long run might result in a stack overrun, especially on a secondary thread). In functional languages, it seems like recursive loops (in source) are the de facto technique, presumably the compiler either converts them to iterative or uses some other implementation to prevent stack issues.

    My question is why do the functional languages (that I know of) prefer to express loops recursively? Is there some way that that construction looks more sensible to humans? Or is it simply that it is more concise?
  2. Catfish_Man macrumors 68030


    Sep 13, 2001
    Portland, OR
    Recursion is fundamental to the underlying mathematical model of functional programming. Iteration requires mutable state (some form of index counter), and cannot be expressed purely in terms of functions. Stack overflow is avoided by tail-call optimization.

    At the most extreme, Church Numerals express even basic arithmetic and numeric values in terms of functions.
  3. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    In iterative languages that don't normally support tail call optimization to limit stack growth a technique called trampolining can be used to minimize stack depth. Generally functional languages support tail call optimization, so stack frames are reused for each call.

  4. softwareguy256 macrumors regular

    Jun 5, 2010
    Functional programming emphasize functions over storing explicit state. Using a loop requires state explicit state in the form of an iterator.


Share This Page