lib/maybe.rb in zx-monads-0.0.4 vs lib/maybe.rb in zx-monads-0.0.5
- old
+ new
@@ -1,26 +1,28 @@
# frozen_string_literal: true
class Maybe
+ attr_reader :value
+
IsBlank = ->(value) { value.nil? || value.to_s.strip&.empty? || !value }
def self.of(...)
new.of(...)
end
- def self.[](...)
+ def self.[](...)
of(...)
end
def of(value)
return None.new if IsBlank[value]
Some.new(value)
rescue StandardError
None.new
end
-
+
def type
to_s.downcase.to_sym
end
def some?
@@ -30,20 +32,21 @@
def none?
type == :none
end
def unwrap
- @value
+ @value
end
def or(value)
IsBlank[@value] ? value : @value
end
def >>(other)
self > other
end
+ alias | >>
def fmap(_)
self
end
@@ -56,11 +59,11 @@
return Maybe[arg.arity > 1 ? arg.curry.call(@value) : arg.call(@value)] if arg.respond_to?(:call)
case arg
in None then self
in Symbol | String then dig(arg)
- end
+ end
rescue StandardError => e
None.new(e.message)
end
alias apply map
@@ -75,11 +78,11 @@
end
def dig(...)
Maybe[@value&.dig(...)]
end
-
+
def dig!(...)
dig(...).unwrap
end
def match(some:, none:)
@@ -119,20 +122,20 @@
def initialize(value = nil)
@value = value
end
- def deconstruct
+ def deconstruct
[@value]
end
def inspect
format("#<Zx::Maybe::#{self}:0x%x value=%s>", object_id, @value.inspect)
end
def to_s
- 'Some'
+ 'Some'
end
def >(other)
other.respond_to?(:call) ? other.call(@value) : other
end
@@ -141,11 +144,11 @@
Maybe[block.call(@value)]
end
end
class None < Maybe
- def self.[](...)
+ def self.[](...)
new(...)
end
def initialize(value = nil)
@value = value
@@ -165,6 +168,6 @@
def map
self
end
end
-end
\ No newline at end of file
+end