jdantonio / functional-ruby

A gem for adding functional programming tools to Ruby. Inspired by Erlang, Clojure, Haskell, and Functional Java.

Home Page:http://www.functional-ruby.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

using each_cons for collectioin ascending?

404pnf opened this issue · comments

commented

This implementation takes twice time, but feels more functional.

def my_ascending?(data, opts={})
  return false if data.nil?
  if block_given?
    data.each_cons(2).all? { |e1, e2| yield(e1) < yield(e2) }
  else
    data.each_cons(2).all? { |e1, e2| e1 < e2  }
  end
end
Benchmark.bmbm do |x|
  x.report('orig') { ascending? (1..1000000).to_a }
  x.report('new') { my_ascending? (1..1000000).to_a }
end
# =Rehearsal ----------------------------------------
# =orig   0.210000   0.000000   0.210000 (  0.212881)
# =new    0.390000   0.000000   0.390000 (  0.395385)
# =------------------------------- total: 0.600000sec
# =           user     system      total        real
# =orig   0.210000   0.000000   0.210000 (  0.211185)
# =new    0.400000   0.010000   0.410000 (  0.397182)
# ==> [#<Benchmark::Tms:0x007fd16900f5e0 @label="orig", @real=0.211185, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.20999999999999996, @total=0.20999999999999996>, #<Benchmark::Tms:0x007fd16b049c70 @label="new", @real=0.397182, @cstime=0.0, @cutime=0.0, @stime=0.009999999999999998, @utime=0.3999999999999999, @total=0.4099999999999999>]

Please feel free to create a Pull Request. I'm happy to have the help.

commented

PR sent