Sha256: 0f1c9fbdee451db53a39b511925b0120a705400ded3824f26a11afee63e5916c

Contents?: true

Size: 1.45 KB

Versions: 20

Compression:

Stored size: 1.45 KB

Contents

require 'concurrent/executors'
require 'concurrent/promise'

module Functions
  private
  def monoid(fn, id)
    fn.define_singleton_method(:identity) do
      id
    end
    fn
  end

  def returns(value)
    -> { value }
  end

  def ignore_and_return(value)
    returns1(value)
  end

  def returns1(value)
    constant(value)
  end

  def constant(value)
    ->(_) { value }
  end

  def identity
    -> (a) { a }
  end

  def call_raises(e)
    -> { raise e }
  end

  alias call_throws call_raises

  def call
    ->(fn) { fn.() }
  end

  def flip(fn)
    ->(a, b) { fn.(b, a) }
  end

  def defer_return(fn)
    ->(value) { defer_apply(fn, value) }
  end

  def defer_apply(fn, value)
    ->() { fn.(value) }
  end

  def call_concurrently(sequence_of_fn)
    pool = Concurrent::CachedThreadPool.new
    begin
      call_concurrently_with_pool(sequence_of_fn, pool)
    ensure
      pool.shutdown
    end
  end

  def call_concurrently_with_pool(sequence_of_fn, pool)
    sequence_of_fn.
        map(as_promise).
        map(execute_with(pool)).
        realise.
        map(realise_promise)
  end

  def as_promise
    -> (fn) {
      Concurrent::Promise.new { fn.() }
    }
  end

  def execute_with(pool)
    -> (promise) {
      pool.post { promise.execute }
      promise
    }
  end

  def realise_promise
    ->(promise) { promise.value! }
  end

  def get_left
    ->(either) { either.left_value }
  end

  def get_right
    ->(either) { either.right_value }
  end
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
totally_lazy-0.1.48 lib/totally_lazy/functions.rb
totally_lazy-0.1.47 lib/totally_lazy/functions.rb
totally_lazy-0.1.46 lib/totally_lazy/functions.rb
totally_lazy-0.1.45 lib/totally_lazy/functions.rb
totally_lazy-0.1.44 lib/totally_lazy/functions.rb
totally_lazy-0.1.43 lib/totally_lazy/functions.rb
totally_lazy-0.1.42 lib/totally_lazy/functions.rb
totally_lazy-0.1.41 lib/totally_lazy/functions.rb
totally_lazy-0.1.39 lib/totally_lazy/functions.rb
totally_lazy-0.1.38 lib/totally_lazy/functions.rb
totally_lazy-0.1.37 lib/totally_lazy/functions.rb
totally_lazy-0.1.36 lib/totally_lazy/functions.rb
totally_lazy-0.1.35 lib/totally_lazy/functions.rb
totally_lazy-0.1.34 lib/totally_lazy/functions.rb
totally_lazy-0.1.33 lib/totally_lazy/functions.rb
totally_lazy-0.1.32 lib/totally_lazy/functions.rb
totally_lazy-0.1.31 lib/totally_lazy/functions.rb
totally_lazy-0.1.30 lib/totally_lazy/functions.rb
totally_lazy-0.1.29 lib/totally_lazy/functions.rb
totally_lazy-0.1.28 lib/totally_lazy/functions.rb