Class: Literal::Variant

Inherits:
Object
  • Object
show all
Defined in:
lib/literal/variant.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, *types) ⇒ Variant

Returns a new instance of Variant.



4
5
6
7
8
9
10
11
# File 'lib/literal/variant.rb', line 4

def initialize(value, *types)
	unless types.any? { |type| type === value }
		raise Literal::TypeError.expected(value, to_be_a: Literal::Union.new(*types))
	end

	@value = value
	@types = types
end

Instance Attribute Details

#valueObject (readonly)

Returns the value of attribute value.



17
18
19
# File 'lib/literal/variant.rb', line 17

def value
  @value
end

Class Method Details

.rescueObject



13
14
15
# File 'lib/literal/variant.rb', line 13

def self.rescue(...)
	Literal::VariantType.new.rescue(...)
end

Instance Method Details

#call(&block) ⇒ Object Also known as: handle



31
32
33
34
35
36
37
# File 'lib/literal/variant.rb', line 31

def call(&block)
	if block
		Literal::Case.new(*@types, &block).call(@value)
	else
		self
	end
end

#deconstructObject



19
20
21
# File 'lib/literal/variant.rb', line 19

def deconstruct
	[value]
end

#deconstruct_keys(_) ⇒ Object



23
24
25
# File 'lib/literal/variant.rb', line 23

def deconstruct_keys(_)
	{ value: @value }
end

#maybe(type) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/literal/variant.rb', line 45

def maybe(type)
	if type === @value
		Literal::Some.new(@value)
	else
		Literal::Nothing
	end
end

#to_procObject



41
42
43
# File 'lib/literal/variant.rb', line 41

def to_proc
	method(:call).to_proc
end

#unionObject



27
28
29
# File 'lib/literal/variant.rb', line 27

def union
	Literal::Union.new(*@types)
end