Module: Trith::Core::Sequence::Constructors

Defined in:
lib/trith/core/sequence.rb

Overview

Sequence constructors.

Instance Method Summary (collapse)

Instance Method Details

- (String) cons(obj, seq) - (Array) cons(obj, seq)

[]

Overloads:

  • - (String) cons(obj, seq)

    Parameters:

    • (#to_s) obj
    • (String) seq

    Returns:

    • (String)
  • - (Array) cons(obj, seq)

    Parameters:

    • (Object) obj
    • (Array, #to_a) seq

    Returns:

    • (Array)

Returns:

  • []



95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/trith/core/sequence.rb', line 95

def cons(obj, seq)
  case seq
    when String
      seq.dup.insert(0, obj.to_s.chr)
    when Array
      seq.dup.unshift(obj)
    else case
      when seq.respond_to?(:to_a)
        seq.to_a.unshift(obj)
      else # TODO: support for `#each`
    end
  end
end

- (Enumerable) iota(n)

Parameters:

  • (Integer, #to_i) n

Returns:

  • (Enumerable)


138
139
140
141
# File 'lib/trith/core/sequence.rb', line 138

def iota(n)
  # TODO: should support negative ranges as well.
  (0...(n.to_i)).to_a # FIXME
end

- (Enumerable) list(n)

Parameters:

  • (Integer, #to_i) n

Returns:

  • (Enumerable)


131
132
133
# File 'lib/trith/core/sequence.rb', line 131

def list(n)
  stack.pop(n.to_i)
end

- (Enumerable) range(a, b)

Parameters:

  • (Integer, #to_i) a
  • (Integer, #to_i) b

Returns:

  • (Enumerable)


147
148
149
150
# File 'lib/trith/core/sequence.rb', line 147

def range(a, b)
  # TODO: should support negative ranges as well.
  ((a.to_i)..(b.to_i)).to_a # FIXME
end

- (Enumerator) seq(obj)

Parameters:

  • (String, #each, #to_enum) obj

Returns:

  • (Enumerator)


68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/trith/core/sequence.rb', line 68

def seq(obj)
  case obj
    when String then obj.each_char
    when Array  then obj.each
    else case
      when obj.respond_to?(:each)
        obj.each
      when obj.respond_to?(:to_enum)
        obj.to_enum
      else
        raise Machine::InvalidOperandError.new(obj, :seq)
    end
  end
end

- (Machine) uncons(seq)

Parameters:

  • (Array, #[], #each) seq

Returns:



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/trith/core/sequence.rb', line 112

def uncons(seq)
  case
    when seq.respond_to?(:[])
      case
        when seq.empty?
          raise Machine::InvalidOperandError.new(seq, :uncons)
        else
          push(seq[0], seq[1..-1]) # FIXME
      end
    when seq.respond_to?(:each)
      uncons(seq.each.to_a)
    else
      raise Machine::InvalidOperandError.new(seq, :uncons)
  end
end