Class: Mon::Monad::List

Inherits:
Mon::Monad show all
Includes:
ChainableMonad
Defined in:
lib/monads/list.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ChainableMonad

#coerce, #method_missing, #respond_to?

Constructor Details

#initialize(list) ⇒ List

Returns a new instance of List.



21
22
23
# File 'lib/monads/list.rb', line 21

def initialize(list)
  @list = list
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Mon::Monad::ChainableMonad

Class Method Details

.[](*list) ⇒ Object

Create a list. Eg: List[1, 2, 3]



26
27
28
# File 'lib/monads/list.rb', line 26

def self.[](*list)
  List.new(list)
end

.valid?(o) ⇒ Boolean

Returns:

  • (Boolean)


82
83
84
# File 'lib/monads/list.rb', line 82

def self::valid?(o)
  o.is_a?(List)
end

Instance Method Details

#==(o) ⇒ Object



74
75
76
# File 'lib/monads/list.rb', line 74

def ==(o)
  eql?(o)
end

#_Object

Alias for #unwrap



42
43
44
# File 'lib/monads/list.rb', line 42

def _
  to_a
end

#bind(&fun) ⇒ Object

Apply fun to all elements of the list (ala map): List[1, 2, 3].map { |i| i + 5 } # ==> List[6, 7, 8]



32
33
34
# File 'lib/monads/list.rb', line 32

def bind &fun
  List.send(:new, @list.map { |i| fun.call(i) }.map { |i| (i.is_a? List) ? i.to_a : i}.flatten(1))
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
67
68
69
70
71
72
# File 'lib/monads/list.rb', line 64

def eql?(other)
  if other.is_a? List
    @list == other.unwrap
  elsif other.is_a? Array
    @list == other
  else
    false
  end
end

#equal?(o) ⇒ Boolean

Returns:

  • (Boolean)


78
79
80
# File 'lib/monads/list.rb', line 78

def equal?(o)
  eql?(o)
end

#to_aObject

Return the array wrapped by the list



56
57
58
# File 'lib/monads/list.rb', line 56

def to_a
  @list
end

#to_sObject



50
51
52
53
# File 'lib/monads/list.rb', line 50

def to_s
  (@list.length > 3) ? (tail = "...") : tail = "" 
  "List[#{ @list.take(3).join(", ") }#{ tail }]"
end