Skip to content

Instantly share code, notes, and snippets.

@AaronLasseigne
Created December 3, 2014 01:27
Show Gist options
  • Save AaronLasseigne/f65ae8b04f335a4c17ed to your computer and use it in GitHub Desktop.
Save AaronLasseigne/f65ae8b04f335a4c17ed to your computer and use it in GitHub Desktop.
Clojure Loops
require 'continuation'
class Clojure
def self.loop(*initial_args, &block)
cont = nil
args = callcc do |c|
class << (cont = c)
alias :recur :call
end
initial_args
end
cont.instance_exec(*args, &block)
end
end
class PrimeFactors
def self.of(number)
Clojure.loop(number, [], 2) do |remaining, divisors, divisor|
if remaining < 2
divisors
elsif remaining % divisor == 0
recur(
(remaining / divisor),
divisors.push(divisor),
divisor
)
else
recur(remaining, divisors, divisor + 1)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment