Sha256: 87b683d1063a6eeb7cd8de64e78f9673d399c11e5007fa86163eecae39bd85df

Contents?: true

Size: 1.25 KB

Versions: 4

Compression:

Stored size: 1.25 KB

Contents

require 'funkr/categories'

# Extends array (as list) capabilities
class Array

  include Funkr::Categories

  class << self
    def unit(e); self.new([e]); end
    alias pure unit
    def mzero; self.new(); end
  end

  ### Categories

  # Array is already a functor with its correct map implementation


  # Array can be made an applicative functor, for example :
  # f = Array.curry_lift_proc{|x,y| x + y}
  # f.apply([0,4]).apply([5,7]) => [5, 7, 9, 11]
  # f.apply([0,4]).apply([]) => []
  include Applicative
  extend Applicative::ClassMethods

  def apply(to)
    map do |f|
      to.map{ |t| f.call(t)}
    end.flatten(1)
  end

  # Array is Alternative whith empty? being zero
  include Alternative

  # [].or_else{[5]} => [5]
  def or_else(&block)
    if empty? then yield
    else self end
  end


  # Array is a monoid with mplus = (+) and mzero = []
  include Monoid
  extend Monoid::ClassMethods

  # [5].mplus([6]) => [5,6]
  def mplus(m_y)
    self + m_y
  end


  # Array is also a monad
  include Monad
  extend Monad::ClassMethods

  def bind(&block)
    self.map(&block).flatten(1)
  end

  def self.box(value)
    if value.nil? then self.mzero
    else self.unit(value) end
  end

  def unbox()
    if self.empty? then nil
    else self.first end
  end


end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
funkr-0.0.25 lib/funkr/extensions/array.rb
funkr-0.0.24 lib/funkr/extensions/array.rb
funkr-0.0.23 lib/funkr/extensions/array.rb
funkr-0.0.22 lib/funkr/extensions/array.rb