Module: Necromancy::Control::Alternative

Extended by:
Necromancy::Control
Includes:
Applicative
Defined in:
lib/necromancy/control/alternative.rb

Instance Method Summary collapse

Methods included from Necromancy::Control

[], call, extended, hiding, new, using

Methods included from Applicative

#**, #<<, #>>

Instance Method Details

#*(callable) ⇒ Necromancy Also known as: __Applicative_Astarisk

Note:
self

a -> b -> c

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

Examples:

require 'necromancy'
N = Necromancy.Alternative.new
f = lambda(&N.+ * N) # == ->(o) { :+.to_proc.(o,o) if o }
f.(nil) # => nil
f.("foo") # => "foofoo"

Parameters:

  • callable (Object)

    a -> b

Returns:

See Also:



32
33
34
35
36
# 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

#empty?(x, *xs) ⇒ Boolean

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.

Returns:

  • (Boolean)


14
15
16
# File 'lib/necromancy/control/alternative.rb', line 14

def empty?(x, *xs)
  not x
end

#|(callable) ⇒ Necromancy

Note:
self

a -> b

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

Examples:

require 'necromancy'
N = Necromancy.Alternative.new
f = lambda(&N | ->(o){"foo"}) # == ->(o){ o ? o : "foo" }
f.(nil) # => "foo"
f.("bar") # => "var"

Parameters:

  • callable (Object)

    a -> b

Returns:

See Also:



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# 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