Class: TAlgebra::Monad::Either

Inherits:
Object
  • Object
show all
Includes:
SingleValued
Defined in:
lib/t_algebra/monad/either.rb

Direct Known Subclasses

Parser

Constant Summary collapse

LEFT =
:left
RIGHT =
:right

Class Method Summary collapse

Instance Method Summary collapse

Methods included from SingleValued

included

Class Method Details

.left(err) ⇒ Object



15
16
17
# File 'lib/t_algebra/monad/either.rb', line 15

def left(err)
  new(is: LEFT, value: err)
end

.pure(value) ⇒ Object Also known as: right



10
11
12
# File 'lib/t_algebra/monad/either.rb', line 10

def pure(value)
  new(is: RIGHT, value: value)
end

Instance Method Details

#==(other) ⇒ Object



52
53
54
# File 'lib/t_algebra/monad/either.rb', line 52

def ==(other)
  to_obj == other.to_obj
end

#bind {|value| ... } ⇒ Object

Yields:

  • (value)

Raises:



27
28
29
30
31
32
# File 'lib/t_algebra/monad/either.rb', line 27

def bind
  raise UseError.new("#bind requires a block") unless block_given?
  return dup if left?

  yield value
end

#fmapObject

Raises:



20
21
22
23
24
25
# File 'lib/t_algebra/monad/either.rb', line 20

def fmap
  raise UseError.new("#fmap requires a block") unless block_given?
  return dup if left?

  self.class.pure(yield(value))
end

#from_eitherObject

Raises:



46
47
48
49
50
# File 'lib/t_algebra/monad/either.rb', line 46

def from_either
  raise UseError.new("#from_either called without block") unless block_given?
  return yield(value) if left?
  value
end

#from_either!Object



42
43
44
# File 'lib/t_algebra/monad/either.rb', line 42

def from_either!
  from_either { |e| raise UnsafeError.new("#from_either! exception. #{e}") }
end

#left?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/t_algebra/monad/either.rb', line 34

def left?
  is == LEFT
end

#right?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/t_algebra/monad/either.rb', line 38

def right?
  is == RIGHT
end

#to_objObject



56
57
58
# File 'lib/t_algebra/monad/either.rb', line 56

def to_obj
  {is.to_s => value, :class => self.class.name}
end