module Necromancy::Control::Alternative

Public Instance Methods

*(callable) click to toggle source

Applies the result of the callable into self unless that result is empty. @see empty?

@note self

a -> b -> c

@param [Object] callable a -> b @return [Necromancy] a -> c @example

require 'necromancy'
N = Necromancy.Alternative.new
f = lambda(&N.+ * N) # == ->(o) { :+.to_proc.(o,o) if o }
f.(nil) # => nil
f.("foo") # => "foofoo"
# File lib/necromancy/control/alternative.rb, line 32
def *(callable)
  str = make_evaluable_string(callable)
  necromancy = "self.empty?(*(xs = (#{str}))) ? xs : (args.concat(xs); #{@necromancy})"
  self.class.new(necromancy, @references.dup)
end
Also aliased as: __Applicative_Astarisk
empty?(x, *xs) click to toggle source

Tests whether the result is empty or not. If it is empty, {#empty?} returns the true, otherwise that returns the false. By default, {#empty?} returns the true, if it is nil or false.

# File lib/necromancy/control/alternative.rb, line 14
def empty?(x, *xs)
  not x
end
|(callable) click to toggle source

Evaluates the callable, unless result of self is empty. otherwise that returns result of self. @see empty?

@note self

a -> b

@param [Object] callable a -> b @return [Necromancy] a -> b @example

require 'necromancy'
N = Necromancy.Alternative.new
f = lambda(&N | ->(o){"foo"}) # == ->(o){ o ? o : "foo" }
f.(nil) # => "foo"
f.("bar") # => "var"
# File lib/necromancy/control/alternative.rb, line 49
def |(callable)
  str = make_evaluable_string(callable)

  if @is_alternative_or
    exprs = [str, *@exprs]
  else
    exprs = [str, @necromancy]
  end

  necromancy = exprs.inject do |else_expr, cond_expr|
    "self.empty?(*(xs = (#{cond_expr}))) ? (#{else_expr}) : xs"
  end

  self.class.new(necromancy, @references.dup).instance_eval do
    @is_alternative_or = true
    @exprs = exprs
    self
  end
end

Protected Instance Methods

__Applicative_Astarisk(callable)
Alias for: *