juli (caladri) wrote in dailysrc,
juli
caladri
dailysrc

  • Mood:

anonymous recursive power-of-2 factorization in Ruby

#! /usr/bin/env ruby

ARGV.each do |w|
  p proc { |f| f.call(f) }.call( proc { |f|
    proc { |y|
      proc { |x|
        if y == 0 then
          [ 0 ]
        else
          [ y & x, f.call(f).call(y & ~x).call(x << 1) ]
        end
      }
    }
  }).call(w.to_i).call(1)
end


For example:


^_^ (juli@beach:~)146% ruby s.rb 8 9 10 11 12 13 14 15
[0, [0, [0, [8, [0]]]]]
[1, [0, [0, [8, [0]]]]]
[0, [2, [0, [8, [0]]]]]
[1, [2, [0, [8, [0]]]]]
[0, [0, [4, [8, [0]]]]]
[1, [0, [4, [8, [0]]]]]
[0, [2, [4, [8, [0]]]]]
[1, [2, [4, [8, [0]]]]]
  • Post a new comment

    Error

    default userpic

    Your IP address will be recorded 

  • 1 comment