Skip to content

Instantly share code, notes, and snippets.

@sdeming
Created January 26, 2012 03:48
Show Gist options
  • Save sdeming/1680865 to your computer and use it in GitHub Desktop.
Save sdeming/1680865 to your computer and use it in GitHub Desktop.
Use callcc for non-recursive factorials.
require 'continuation'
class FactorialsInCC
def fact(n)
factorial = 1
callcc { |fact_jmp| @fact_jmp = fact_jmp }
factorial *= n
n -= 1
@fact_jmp.call if n > 1
factorial
end
end
puts FactorialsInCC.new.fact(ARGV[0].to_i)
@sdeming
Copy link
Author

sdeming commented Jan 26, 2012

Been sitting on this a while. Non-recursive using callcc for quick jump back. Obviously you don't need to be recursive to do factorials anyway, but it's a neat alternative to a loop.

@fact_jmp.call = goto

I love goto. It's so efficient.

@jmazzi
Copy link

jmazzi commented Jan 26, 2012

Cool stuff. Neat way to queue up some logic.

Careful though; Its kinda like setting a trap. Thing is, set enough traps and you will eventually catch yourself in one.

@sdeming
Copy link
Author

sdeming commented Jan 26, 2012

It gets really cool when you start passing the continuations around.

@jmazzi
Copy link

jmazzi commented Jan 26, 2012

Haha, i'm just busting your balls. It really is cool stuff. Have you done anything useful with it yet?

@sdeming
Copy link
Author

sdeming commented Jan 27, 2012

Hah, not yet. At least not in Ruby. In Ruby, I think callcc is a solution looking for a problem. A good use case may not actually exist.

@jmazzi
Copy link

jmazzi commented Jan 27, 2012 via email

@sdeming
Copy link
Author

sdeming commented Jan 27, 2012

Did not! Er, where?

@jmazzi
Copy link

jmazzi commented Jan 27, 2012 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment