• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag
 

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Recursive blocks
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Recursive blocks


  • Subject: Re: Recursive blocks
  • From: Glen Low <email@hidden>
  • Date: Thu, 27 Jan 2011 13:47:41 +0800

Chris, All

Apparently you can do recursive blocks, according to Bill Bumgarner.

http://www.friday.com/bbum/2009/08/29/blocks-tips-tricks/

The "trick" seems to be to declare the block variable with the __block modifier and break up declaration and initialization, this seems to keep both compiler and analyzer happy.

int main (int argc, const char * argv[]) {
__block int (^factorial2)(int);
factorial2 = ^(int n)
{
if (n == 1)
return 1;
else
return n * factorial2(n-1);
};

   int i = factorial2(10);

   return 0;
}

Why do this instead of a block calling a recursive function? Same reason why we use blocks -- it's more convenient when you have to capture other local variables from the scope, otherwise the (private) recursive function will have to declare them all as parameters, and (public) wrapper function and block therein will have to copy or forward all the necessary variables to the recursive function.

Essentially writing a recursive function involves naming the private code that is recursive (in order to recurse). With blocks this naming can be hidden as an implementation detail behind the public function wrapping it.
 
On 27/01/2011, at 11:20 AM, Chris Suter wrote:

Hi Glen,

On Thu, Jan 27, 2011 at 2:04 PM, Chris Suter <email@hidden> wrote:

For example:
[snip]

Sorry, my example had an obvious bug in it; I forgot to copy the block before returning it, but hopefully you got my point. Also, sorry about the formatting. I blame Gmail.

Kind regards,

Chris




Cheers, Glen Low


---
pixelglow software | simply brilliant stuff
www.pixelglow.com
aim: pixglen
twitter: pixelglow

 _______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden

  • Follow-Ups:
    • Re: Recursive blocks
      • From: Chris Suter <email@hidden>
References: 
 >Recursive blocks (From: Glen Low <email@hidden>)
 >Re: Recursive blocks (From: Chris Suter <email@hidden>)
 >Re: Recursive blocks (From: Chris Suter <email@hidden>)

  • Prev by Date: Re: Recursive blocks
  • Next by Date: Re: Recursive blocks
  • Previous by thread: Re: Recursive blocks
  • Next by thread: Re: Recursive blocks
  • Index(es):
    • Date
    • Thread