Module: Porolog

Defined in:
lib/porolog.rb,
lib/porolog/goal.rb,
lib/porolog/rule.rb,
lib/porolog/tail.rb,
lib/porolog/error.rb,
lib/porolog/scope.rb,
lib/porolog/value.rb,
lib/porolog/variable.rb,
lib/porolog/arguments.rb,
lib/porolog/predicate.rb,
lib/porolog/instantiation.rb

Overview

lib/porolog/instantiation.rb - Plain Old Ruby Objects Prolog Engine – Instantiation

Luis Esteban   2 May 2018
  created

Defined Under Namespace

Classes: Arguments, Goal, Instantiation, NoGoalError, PorologError, Predicate, Rule, Scope, Tail, Value, Variable

Constant Summary collapse

VERSION =

The most recent version of the Porolog gem.

'0.0.8'.freeze
VERSION_DATE =

The most recent date of when the VERSION changed.

'2020-07-06'.freeze
UNKNOWN_TAIL =

Represents an unknown tail of a list.

Object.new
UNKNOWN_ARRAY =

Represents a list where all elements are unknown.

[UNKNOWN_TAIL].freeze

Instance Method Summary collapse

Instance Method Details

#expand_splat(array) ⇒ Array

Expands a superfluous splat.

Parameters:

  • array (Array)

    the given Array.

Returns:

  • (Array)

    the given Array with any superfluous splats expanded.



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/porolog.rb', line 339

def expand_splat(array)
  array = array.first.value if array.is_a?(Array) && array.length == 1 && array.first.is_a?(Tail)
  
  if array.is_a?(Array) && array.last.is_a?(Tail) && array.last.value.is_a?(Array)
    array = [*array[0...-1], *array.last.value]
  end
  
  if array.is_a?(Array)
    array = array.map{|element|
      expand_splat(element)
    }
  end
  
  array
end

#has_tail?(value, apply_value = true) ⇒ Boolean

Returns whether the provided value has a Tail.

Parameters:

  • value (Object)

    the provided value.

Returns:

  • (Boolean)

    whether the provided value has a Tail.



326
327
328
329
330
331
332
333
334
# File 'lib/porolog.rb', line 326

def has_tail?(value, apply_value = true)
  value = value.value if value.respond_to?(:value) && apply_value
  
  if value.is_a?(Array)
    value.last == UNKNOWN_TAIL || value.last.is_a?(Tail)
  else
    false
  end
end

#instantiate_unifications(unifications) ⇒ Boolean

Instantiates the unifications from an attempt to unify.

Parameters:

  • unifications (Array)

    unifications to instantiate.

Returns:

  • (Boolean)

    whether the instantiations could be made.



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/porolog.rb', line 89

def instantiate_unifications(unifications)
  # -- Gather Unifications --
  goals_variables = {}
  
  return_false = false
  unifications.each do |unification|
    left, right, left_goal, right_goal = unification
    
    goals_variables[left_goal]       ||= {}
    goals_variables[left_goal][left] ||= []
    goals_variables[left_goal][left] << [right_goal,right]
    
    return_false = true if goals_variables[left_goal][left].map(&:last).reject{|value|
      value.is_a?(Variable) || value.is_a?(Symbol)
    }.uniq.size > 1
    
    return false if return_false
  end
  
  # -- Make Instantiations --
  instantiations = []
  consistent     = true
  
  goals_variables.each do |goal,variables|
    variables.each do |name,others|
      others.each do |other_goal,other|
        instantiation = goal.instantiate(name, other, other_goal)
        if instantiation
          instantiations << instantiation
        else
          consistent = false
        end
      end
    end
  end
  
  # -- Revert if inconsistent --
  instantiations.each(&:remove) unless consistent
  
  consistent
end

#predicate(*names) ⇒ Porolog::Predicate+

A convenience method to create a Predicate, along with a method that returns an Arguments based on the arguments provided to the method.

Examples:

predicate :combobulator
combobulator(:x,:y)       # --> Porolog::Arguments

Parameters:

  • names (Array<#to_sym>)

    names of the Predicates to create.

Returns:



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/porolog.rb', line 45

def predicate(*names)
  names = [names].flatten
  
  predicates = names.map{|name|
    method     = name.to_sym
    predicate  = Predicate.new(name)
    Object.class_eval{
      remove_method(method) if public_method_defined?(method)
      define_method(method){|*args|
        predicate.(*args)
      }
    }
    predicate
  }
  
  predicates.size > 1 && predicates || predicates.first
end

#unify(left, right, left_goal, right_goal = left_goal, visited = []) ⇒ Array?

Attempt to unify two entities of two goals.

Parameters:

  • left (Object)

    left hand side entity.

  • right (Object)

    right hand side entity.

  • left_goal (Porolog::Goal)

    goal of left hand side entity.

  • right_goal (Porolog::Goal) (defaults to: left_goal)

    goal of right hand side entity.

  • visited (Array) (defaults to: [])

    prevents infinite recursion.

Returns:

  • (Array)

    an Array of unifications when the left hand side can be unified with the right hand.

  • (nil)

    nil if they cannot be unified.



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/porolog.rb', line 139

def unify(left, right, left_goal, right_goal = left_goal, visited = [])
  right_goal ||= left_goal
  goals     = [left_goal, right_goal].uniq
  signature = [left.type, right.type]
  
  # -- Nil is Uninstantiated (can always unify) --
  return [] unless left && right
  
  # -- Set HeadTail Goals --
  case signature
    when [:atomic, :atomic]
      if left == right
        []
      else
        msg = "Cannot unify because #{left.inspect} != #{right.inspect} (atomic != atomic)"
        goals.each{|goal| goal.log << msg }
        nil
      end
    
    when [:array, :array]
      _merged, unifications = unify_arrays(left, right, left_goal, right_goal, visited)
      if unifications
        unifications
      else
        msg = "Cannot unify because #{left.inspect} != #{right.inspect} (array != array)"
        goals.each{|goal| goal.log << msg }
        nil
      end
    
    when [:variable, :atomic]
      left_value  = left_goal.value_of(left, nil, visited)
      right_value = right
      if left_value == right_value || left_value.is_a?(Variable) || left_value.nil?
        [[left, right, left_goal, right_goal]]
      else
        msg = "Cannot unify because #{left_value.inspect} != #{right_value.inspect} (variable != atomic)"
        goals.each{|goal| goal.log << msg }
        nil
      end
    
    when [:atomic, :variable]
      left_value  = left
      right_value = right_goal.value_of(right, nil, visited)
      if left == right_value || right_value.is_a?(Variable) || right_value.nil?
        [[right,left,right_goal,left_goal]]
      else
        msg = "Cannot unify because #{left_value.inspect} != #{right_value.inspect} (atomic != variable)"
        goals.each{|goal| goal.log << msg }
        nil
      end
    
    when [:variable, :variable]
      left_value  = left_goal.value_of(left, nil, visited)
      right_value = right_goal.value_of(right, nil, visited)
      if left_value == right_value || left_value.is_a?(Variable) || right_value.is_a?(Variable) || left_value.nil? || right_value.nil?
        [[left, right, left_goal, right_goal]]
      else
        msg = "Cannot unify because #{left_value.inspect} != #{right_value.inspect} (variable != variable)"
        goals.each{|goal| goal.log << msg }
        nil
      end
    
    when [:variable, :array]
      left_value  = left_goal.value_of(left, nil, visited)
      right_value = right
      if left_value == right_value || left_value.is_a?(Variable) || left_value == UNKNOWN_ARRAY || left_value.nil?
        [[left, right, left_goal, right_goal]]
      elsif left_value.type == :array
        _merged, unifications = unify_arrays(left_value, right, left_goal, right_goal, visited)
        if unifications
          unifications
        else
          msg = "Cannot unify because #{left_value.inspect} != #{right.inspect} (variable/array != array)"
          goals.each{|goal| goal.log << msg }
          nil
        end
      else
        msg = "Cannot unify because #{left_value.inspect} != #{right_value.inspect} (variable != array)"
        goals.each{|goal| goal.log << msg }
        nil
      end
    
    when [:array, :variable]
      left_value  = left
      right_value = right_goal.value_of(right, nil, visited)
      if left_value == right_value || right_value.is_a?(Variable) || right_value == UNKNOWN_ARRAY || right_value.nil?
        [[right, left, right_goal, left_goal]]
      elsif right_value.type == :array
        _merged, unifications = unify_arrays(left, right_value, left_goal, right_goal, visited)
        if unifications
          unifications
        else
          msg = "Cannot unify because #{left.inspect} != #{right_value.inspect} (variable/array != array)"
          goals.each{|goal| goal.log << msg }
          nil
        end
      else
        msg = "Cannot unify because #{left_value.inspect} != #{right_value.inspect} (array != variable)"
        goals.each{|goal| goal.log << msg }
        nil
      end
    
    when [:array,:atomic], [:atomic,:array]
      msg = "Cannot unify #{left.inspect} with #{right.inspect}"
      goals.each{|goal| goal.log << msg }
      nil
    
    else
      # :nocov:
      raise UnknownUnificationSignature, "UNKNOWN UNIFICATION SIGNATURE: #{signature.inspect}"
      # :nocov:
  end
end

#unify_arrays(left, right, left_goal, right_goal = left_goal, visited = []) ⇒ Array<Array, Array>?

Attempt to unify two Arrays.

Parameters:

  • left (Array)

    left hand side Array.

  • right (Array)

    right hand side Array.

  • left_goal (Porolog::Goal)

    goal of left hand side Array.

  • right_goal (Porolog::Goal) (defaults to: left_goal)

    goal of right hand side Array.

  • visited (Array) (defaults to: [])

    prevents infinite recursion.

Returns:

  • (Array<Array, Array>)

    the merged Array and the unifications to be instantiated.

  • (nil)

    if the Arrays cannot be unified.



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/porolog.rb', line 261

def unify_arrays(left, right, left_goal, right_goal = left_goal, visited = [])
  arrays        = [left,       right]
  arrays_goals  = [left_goal,  right_goal]
  arrays_values = arrays.map(&:value)
  
  # -- Trivial Unifications --
  return [left_goal. variablise(left), []] if right == UNKNOWN_ARRAY
  return [right_goal.variablise(right),[]] if left  == UNKNOWN_ARRAY
  
  # -- Validate Arrays --
  unless arrays_values.all?{|array| array.is_a?(Array) || array == UNKNOWN_TAIL }
    msg = "Cannot unify a non-array with an array: #{left.inspect} with #{right.inspect}"
    arrays_goals.uniq.each{|goal| goal.log  << msg }
    return nil
  end
  
  # -- Count Tails --
  number_of_arrays = arrays.size
  number_of_tails  = arrays.count{|array| has_tail?(array) }
  
  # -- Handle Tails --
  if number_of_tails == 0
    unify_arrays_with_no_tails(arrays, arrays_goals, visited)
  elsif number_of_tails == number_of_arrays
    unify_arrays_with_all_tails(arrays, arrays_goals, visited)
  else
    unify_arrays_with_some_tails(arrays, arrays_goals, visited)
  end
end

#unify_arrays_with_all_tails(arrays, arrays_goals, visited) ⇒ Array<Array, Array>?

Unifies Arrays where each Array has a Tail.

Parameters:

  • arrays (Array<Array>)

    the Arrays to be unified.

  • arrays_goals (Array<Porolog::Goal>)

    the Goals of the Arrays to be unified.

  • visited (Array)

    prevents infinite recursion.

Returns:

  • (Array<Array, Array>)

    the merged Array and the unifications to be instantiated.

  • (nil)

    if the Arrays cannot be unified.



529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
# File 'lib/porolog.rb', line 529

def unify_arrays_with_all_tails(arrays, arrays_goals, visited)
  unifications = []
  merged       = []
  
  # -- All tails --
  signature = arrays.map(&:headtail?)
  arrays = arrays.map{|array|
    expand_splat(array.headtail? ? array : array.value)
  }
  signature = arrays.map(&:headtail?)
  
  # -- Unify Embedded Arrays --
  if arrays.any?{|array| array.type == :variable }
    unifications = unify(*arrays[0...2], *arrays_goals[0...2], visited)
    if unifications
      merged = arrays.reject{|value| value.type == :variable }.first || nil
      return [merged, unifications]
    else
      msg = "Cannot unify embedded arrays: #{arrays[0...2].map(&:value).map(&:inspect).join(' with ')}"
      arrays_goals.uniq.each do |goal|
        goal.log << msg
      end
      return nil
    end
  end
  
  signature = arrays.map(&:headtail?)
  unifications = []
  merged       = []
  
  if signature.all?
    merged, unifications = unify_headtail_with_headtail(arrays, arrays_goals, visited)
  elsif signature.map(&:!).all?
    merged, unifications = unify_tail_with_tail(arrays, arrays_goals, visited)
  else
    merged, unifications = unify_headtail_with_tail(arrays, arrays_goals, visited)
  end
  
  if unifications
    return [merged, unifications]
  else
    return nil
  end
end

#unify_arrays_with_no_tails(arrays, arrays_goals, visited) ⇒ Array<Array, Array>?

Unifies Arrays where no Array has a Tail.

Parameters:

  • arrays (Array<Array>)

    the Arrays to be unified.

  • arrays_goals (Array<Porolog::Goal>)

    the Goals of the Arrays to be unified.

  • visited (Array)

    prevents infinite recursion.

Returns:

  • (Array<Array, Array>)

    the merged Array and the unifications to be instantiated.

  • (nil)

    if the Arrays cannot be unified.



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'lib/porolog.rb', line 361

def unify_arrays_with_no_tails(arrays, arrays_goals, visited)
  # -- Validate Arrays --
  if arrays.any?{|array| has_tail?(array) }
    msg = "Wrong unification method called: no_tails but one or more of #{arrays.inspect} has a tail"
    arrays_goals.uniq.each do |goal|
      goal.log << msg
    end
    return nil
  end
  
  # -- Trivial Unifications --
  return [[],[]] if arrays.empty?
  
  # -- Ensure Arrays elements have Goals --
  arrays_values = arrays.dup
  arrays_goals  = arrays_goals.dup
  
  arrays.each_with_index do |array, index|
    if array.is_a?(Value)
      arrays_goals[index] ||= array.goal
      arrays_values[index]  = array.value
    end
    
    if arrays_goals[index].nil?
      value_with_goal = array.find{|element| element.respond_to?(:goal) }
      arrays_goals[index] = value_with_goal.goal if value_with_goal && value_with_goal.goal
    end
    
    if arrays_goals[index].nil?
      raise NoGoalError, "Array #{array.inspect} has no goal for unification"
    end
    
    arrays_values[index] = expand_splat(arrays_values[index])
  end
  
  # -- Check whether all arrays are an Array --
  unless arrays_values.all?{|array| array.is_a?(Array) }
    merged, unifications = unify_many_arrays(arrays.map{|array| [array] }, arrays_goals, visited)
    return [merged] + [unifications]
  end
  
  arrays_variables = arrays_goals.zip(arrays)
  
  # -- Remap Arrays so that they are variablised and valuised with their Goals --
  new_arrays = []
  arrays_variables.each do |goal,variables|
    new_array = variables.map{|variable|
      value = goal.value_of(variable, nil, visited).value
      value = variable if value == UNKNOWN_TAIL || value == UNKNOWN_ARRAY
      
      if value.type == :variable
        value = goal.variable(value)
      elsif value.is_a?(Array)
        value = value.map{|element|
          if element.type == :variable
            goal.variable(element)
          elsif element.is_a?(Value)
            element
          elsif element.is_a?(Tail)
            element
          else
            goal.value(element)
          end
        }
      elsif !value.is_a?(Value)
        value = goal.value(value)
      end
      value
    }
    new_arrays << new_array
  end
  arrays = new_arrays
  
  # -- Unify All Elements --
  sizes = arrays.map(&:length).uniq
  if sizes.size <= 1
    # -- Arrays are the same length --
    zipped       = arrays[0].zip(*arrays[1..-1]).map(&:uniq).map(&:compact).uniq
    unifications = []
    merged       = []
    
    # TODO: Change these names
    zipped.each_with_index{|values_to_unify, index|
      values_to_unify_values = values_to_unify.map{|value|
        value_value = value.value
        if value_value == UNKNOWN_TAIL || value_value == UNKNOWN_ARRAY
          value
        else
          value_value
        end
      }.compact.uniq
      
      if values_to_unify_values.size <= 1
        # -- One Value --
        value = values_to_unify_values.first
        if value.type == :variable
          merged << nil
        else
          merged << value.value
        end
      else
        if values_to_unify_values.all?{|value| value.is_a?(Array) }
          submerged, subunifications = unify_many_arrays(values_to_unify_values, arrays_goals)
          if subunifications
            merged << submerged
            unifications += subunifications
          else
            msg = "Cannot unify: #{values_to_unify_values.map(&:inspect).join(' with ')}"
            arrays_goals.uniq.each{|goal| goal.log << msg }
            return nil
          end
        elsif values_to_unify.variables.empty?
          # -- Incompatible Values --
          incompatible_values = values_to_unify.map(&:value)
          msg = "Cannot unify incompatible values: #{incompatible_values.compact.map(&:inspect).join(' with ')}"
          arrays_goals.uniq.each{|goal| goal.log << msg }
          return nil
        else
          # -- Potentially Compatible Values/Variables --
          nonvariables = values_to_unify.map(&:value).compact.reject{|value| value.type == :variable }
          
          values_to_unify.reject{|value| value.value.nil? }.combination(2).each do |vl, vr|
            subunifications = unify(vl, vr, vl.goal, vr.goal, visited)
            if subunifications
              unifications += subunifications
            else
              msg = "Cannot unify: #{vl.inspect} with #{vr.inspect}"
              [vl.goal, vr.goal].uniq.each{|goal| goal.log << msg }
              return nil
            end
          end
          
          if nonvariables.size > 1
            subgoals = arrays_goals.dup
            nonvariables.each_with_index do |nonvariable, index|
              if nonvariable.respond_to?(:goal)
                subgoal = nonvariable.goal
                subgoals[index] = subgoal if subgoal
              end
            end
            subgoals = subgoals[0...nonvariables.size]
            merged_nonvariables, _nonvariable_unifications = unify_many_arrays(nonvariables, subgoals, visited)
          else
            merged_nonvariables      = nonvariables
          end
          
          merged_value = merged_nonvariables
          merged_value = [nonvariables.first.value] if merged_value.nil? || merged_value == []
          merged += merged_value
        end
      end
    }
    
    [merged, unifications]
  else
    # -- Arrays are different lengths --
    msg = "Cannot unify arrays of different lengths: #{arrays_values.map(&:inspect).join(' with ')}"
    arrays_goals.uniq.each{|goal| goal.log << msg }
    nil
  end
end

#unify_arrays_with_some_tails(arrays, arrays_goals, visited) ⇒ Array<Array, Array>?

Unifies Arrays where Arrays with a Tail are unified with Arrays without a Tail.

Parameters:

  • arrays (Array<Array>)

    the Arrays to be unified.

  • arrays_goals (Array<Porolog::Goal>)

    the Goals of the Arrays to be unified.

  • visited (Array)

    prevents infinite recursion.

Returns:

  • (Array<Array, Array>)

    the merged Array and the unifications to be instantiated.

  • (nil)

    if the Arrays cannot be unified.



927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
# File 'lib/porolog.rb', line 927

def unify_arrays_with_some_tails(arrays, arrays_goals, visited)
  # -- Variablise Arrays --
  arrays = arrays_goals.zip(arrays).map{|goal,array|
    if goal.nil?
      goal = array.goal        if array.is_a?(Value)
      if goal.nil? && array.is_a?(Array)
        v = array.find{|element| element.respond_to?(:goal) }
        goal = v && v.goal
      end
    end
    goal = arrays_goals.compact.last if goal.nil?
    raise NoGoalError, "#{array.inspect} has no associated goal!  Cannot variablise!" if goal.nil? || !goal.is_a?(Goal)
    goal.variablise(array)
  }
  
  # -- Some unknown tails --
  tailed_arrays, finite_arrays = arrays.partition{|array| has_tail?(array) }
  
  finite_sizes = finite_arrays.reject{|finite_array| finite_array.type == :variable }.map(&:size).uniq
  
  unless finite_sizes.size == 1
    msg = "Cannot unify different sizes of arrays: #{arrays.map(&:inspect).join(' with ')}"
    arrays_goals.uniq.each do |goal|
      goal.log << msg
    end
    return nil
  end
  
  exact_size = finite_sizes.first
  
  tails         = tailed_arrays.map{|array| [array[0...-1].size,array.last,arrays_goals[arrays.index(array)]] }
  tailed_arrays = tailed_arrays.map{|array| array[0...-1] }
  
  # -- Fail --
  #   [nil,nil,nil,nil,...]
  #   [1,  2,  3]
  min_tailed_size = tailed_arrays.map(&:size).max
  
  if min_tailed_size > exact_size
    msg = "Cannot unify enough elements: #{arrays.map(&:inspect).join(' with ')}"
    arrays_goals.uniq.each do |goal|
      goal.log << msg
    end
    return nil
  end
  
  # -- Succeed --
  #   [nil,nil,...]
  #   [1,  2,  3]
  arrays = tailed_arrays + finite_arrays
  
  zip_arrays = arrays.map{|array|
    if array.is_a?(Value) && array.value.is_a?(Array)
      array.value.map{|v|
        if v.type == :variable
          array.goal.variable(v)
        else
          array.goal.value(v)
        end
      }
    elsif array.type == :variable
      array.goal.value_of(array)
    else
      array
    end
  }.select{|array| array.is_a?(Array) }
  
  zipped       = ([nil] * exact_size).zip(*zip_arrays).map(&:uniq).map(&:compact)
  merged       = []
  unifications = []
  
  zipped.each{|zipped_values|
    values = zipped_values
    value = values.reject{|v| v.value(visited).nil? }.compact.uniq
    value_values = value.map(&:value).compact.uniq
    if value_values.size <= 1
      m = value.first.value
      m = nil if m.type == :variable
      merged << m
    else
      if values.variables.empty?
        msg = "Cannot unify enough elements: #{values.map(&:inspect).join(' with ')}"
        arrays_goals.uniq.each do |goal|
          goal.log << msg
        end
        return nil
      else
        _variables, nonvariables = values.reject{|v| v.value.nil? }.partition{|element| element.type == :variable }
        if nonvariables.value.uniq.size <= 1
          m = nonvariables.first.value
          m = nil if m.type == :variable
          merged << m
          
          value.combination(2).each do |vl, vr|
            if vl.type == :variable
              unifications << [vl, vr, vl.goal, vr.goal]
            elsif vr.type == :variable
              unifications << [vr, vl, vr.goal, vl.goal]
            end
          end
        else
          msg = "Cannot unify non-variables: #{nonvariables.value.uniq.map(&:inspect).join(' with ')}"
          arrays_goals.uniq.each do |goal|
            goal.log << msg
          end
          return nil
        end
      end
    end
  }
  
  tails.each do |head_size,tail,goal|
    next if tail == UNKNOWN_TAIL
    merged_goals = arrays_goals - [goal] + [goal]
    unifications << [tail.value(visited).value(visited), merged[head_size..-1], goal, merged_goals.compact.first]
  end
  
  [merged, unifications]
end

#unify_goals(goal, subgoal) ⇒ Boolean

Unify the Arguments of a Goal and a sub-Goal.

Parameters:

  • goal (Porolog::Goal)

    a Goal to solve a Predicate for specific Arguments.

  • subgoal (Porolog::Goal)

    a sub-Goal to solve the Goal following the Rules of the Predicate.

Returns:

  • (Boolean)

    whether the Goals can be unified.



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/porolog.rb', line 67

def unify_goals(goal, subgoal)
  if goal.arguments.predicate == subgoal.arguments.predicate
    unifications = unify(goal.arguments.arguments, subgoal.arguments.arguments, goal, subgoal)
    if unifications
      instantiate_unifications(unifications)
    else
      msg = "Could not unify goals: #{goal.arguments.arguments.inspect} !~ #{subgoal.arguments.arguments.inspect}"
      goal.log << msg
      subgoal.log << msg
      false
    end
  else
    msg = "Cannot unify goals because they are for different predicates: #{goal.arguments.predicate.name.inspect} and #{subgoal.arguments.predicate.name.inspect}"
    goal.log << msg
    subgoal.log << msg
    false
  end
end

#unify_headtail_with_headtail(arrays, arrays_goals, visited) ⇒ Array<Array, Array>?

Unifies Arrays where each Array is a Head/Tail array.

Parameters:

  • arrays (Array<Array>)

    the Arrays to be unified.

  • arrays_goals (Array<Porolog::Goal>)

    the Goals of the Arrays to be unified.

  • visited (Array)

    prevents infinite recursion.

Returns:

  • (Array<Array, Array>)

    the merged Array and the unifications to be instantiated.

  • (nil)

    if the Arrays cannot be unified.



866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
# File 'lib/porolog.rb', line 866

def unify_headtail_with_headtail(arrays, arrays_goals, visited)
  unless arrays.all?(&:headtail?)
    msg = "Wrong method called to unify #{arrays.inspect}"
    arrays_goals.uniq.each do |goal|
      goal.log << msg
    end
    return nil
  end
  
  unifications = []
  
  arrays.combination(2).each do |pair|
    # -- Collect Goals --
    pair_goals = pair.map{|array| arrays_goals[arrays.index(array)] }
    
    # -- Unify Heads --
    heads = pair.map(&:first)
    subunifications = unify(*heads, *pair_goals, visited)
    if subunifications
      unifications += subunifications
    else
      unifications = nil
      msg = "Cannot unify headtail heads: #{heads.map(&:inspect).join(' with ').inspect}"
      pair_goals.uniq.each do |goal|
        goal.log  << msg
      end

      return nil
    end
    
    # -- Unify Tails --
    tails = pair.map(&:last).map{|tail| tail.value(visited) }
    subunifications = unify(*tails, *pair_goals, visited)
    if subunifications
      unifications += subunifications
    else
      unifications = nil
      msg = "Cannot unify headtail tails: #{tails.map(&:inspect).join(' with ')}"
      pair_goals.uniq.each do |goal|
        goal.log  << msg
      end

      return nil
    end
  end
  
  # -- Determine Merged --
  merged = [
    arrays.map(&:first).map{|head| head.value(visited) }.reject{|head| head.type == :variable }.first,
    *arrays.map(&:last).map{|tail| tail.value(visited) }.reject{|tail| tail.type == :variable || tail == UNKNOWN_TAIL }.first || UNKNOWN_TAIL,
  ]
  
  [merged, unifications]
end

#unify_headtail_with_tail(arrays, arrays_goals, visited) ⇒ Array<Array, Array>?

Unifies Arrays where the Arrays are a mixture of Head/Tail and non-Head/Tail arrays.

Parameters:

  • arrays (Array<Array>)

    the Arrays to be unified.

  • arrays_goals (Array<Porolog::Goal>)

    the Goals of the Arrays to be unified.

  • visited (Array)

    prevents infinite recursion.

Returns:

  • (Array<Array, Array>)

    the merged Array and the unifications to be instantiated.

  • (nil)

    if the Arrays cannot be unified.



670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# File 'lib/porolog.rb', line 670

def unify_headtail_with_tail(arrays, arrays_goals, visited)
  # -- Validate Arrays --
  unless arrays.all?{|array| has_tail?(array, false) }
    msg = "Wrong method called to unify #{arrays.inspect}"
    arrays_goals.uniq.each do |goal|
      goal.log << msg
    end
    return nil
  end
  
  merged       = []
  unifications = []
  
  # -- Variablise Arrays --
  arrays = arrays_goals.zip(arrays).map do |goal, array|
    goal.variablise(array)
  end
  
  # -- Determine the fixed length (if any) --
  fixed_length = nil
  arrays.each do |array|
    unless has_tail?(array)
      array_length = array.value.size
      fixed_length ||= array_length
      unless fixed_length == array_length
        array.goal.log << "Cannot unify #{array.value.inspect} because it has a different length from #{fixed_length}"
        return nil
      end
    end
  end
  
  # -- Partition Arrays --
  headtail_arrays, tail_arrays = arrays.partition(&:headtail?)
  
  # -- Unify All HeadTail Arrays --
  if headtail_arrays.size > 1
    headtail_goals = headtail_arrays.map{|array| array.goal }
    merged_headtails, headtail_unifications = unify_headtail_with_headtail(headtail_arrays, headtail_goals, visited)
    unless merged_headtails
      msg = "Could not unify headtail arrays: #{headtail_arrays.map(&:value).map(&:inspect).join(' with ')}"
      headtail_goals.uniq.each do |goal|
        goal.log << msg
      end
      return nil
    end
    unifications += headtail_unifications
    
    if merged_headtails.length > merged.length
      merged += [[]] * (merged_headtails.length - merged.length)
    end
    
    # TODO: Remove flatten
    merged = merged.zip(merged_headtails).map(&:flatten)
  end
  
  # -- Unify All Tail Arrays --
  if tail_arrays.size > 1
    tail_goals = tail_arrays.map{|array| array.goal }
    merged_tails, tail_unifications = unify_tail_with_tail(tail_arrays, tail_goals, visited)
    return nil unless merged_tails
    unifications += tail_unifications
    
    if merged_tails.length > merged.length
      merged += [[]] * (merged_tails.length - merged.length)
    end
    
    # TODO: Remove flatten
    merged = merged.zip(merged_tails).map(&:flatten).map{|merge_values|
      merge_values.map{|value|
        if value == UNKNOWN_TAIL
          nil
        else
          value
        end
      }
    }.map(&:compact)
  end
  
  # -- Combine HeadTail Arrays and Tail Arrays --
  headtail_arrays.product(tail_arrays).each do |pair|
    # == :head/:tail ~~ [1,2,3]/:tail ==
    # -- Extract Elements --
    left       = expand_splat(pair.first)
    left_head  = left.head
    left_tail  = left.tail
    
    right      = expand_splat(pair.last)
    right_head = right.head
    right_tail = right.tail
    
    # -- Expand Tail --
    left_tail  = expand_splat(left_tail)
    right_tail = expand_splat(right_tail)
    
    # -- Determine Goals --
    left_goal  = pair.first.goal
    right_goal = pair.last.goal
    
    # -- Unify Heads --
    head_unifications = unify(left_head, right_head, left_goal, right_goal, visited)
    if head_unifications.nil?
      msg = "Cannot unify heads: #{left_head.inspect} with #{right_head.inspect}"
      left_goal.log  << msg
      right_goal.log << msg unless right_goal == left_goal
      return nil
    end
    unifications += head_unifications
    
    # -- Unify Tails --
    tail_unifications = unify(left_tail, right_tail, left_goal, right_goal, visited)
    if tail_unifications.nil?
      msg = "Cannot unify tails: #{left_tail.inspect} with #{right_tail.inspect}"
      left_goal.log  << msg
      right_goal.log << msg unless right_goal == left_goal
      return nil
    end
    unifications += tail_unifications
    
    # -- Determine Merged and Unifications --
    left_reassembled  = [left_head,  *left_tail ]
    right_reassembled = [right_head, *right_tail]
    max_length = [left_reassembled.length, right_reassembled.length].max
    
    if max_length > merged.length
      merged += [[]] * (max_length - merged.length)
    end
    
    merged = merged.zip(left_reassembled ).map(&:flatten)
    merged = merged.zip(right_reassembled).map(&:flatten)
  end
  
  merged = merged.value
  merged = merged.map(&:value)
  
  # TODO: Cleanup names
  # TODO: Flatten out tails
  #   E.g.  [nil, [2, 3], ...] should be [nil, 2, 3, ...]
  is_tails = []
  merged = merged.value.map{|elements|
    sorted_elements = elements.reject{|element|
      element.is_a?(Variable)
    }.uniq.compact.sort_by{|element|
      case element.type
        when :atomic
          0
        when :array
          if [UNKNOWN_TAIL, UNKNOWN_ARRAY].include?(element)
            3
          else
            1
          end
        else
          # :nocov:
          # There are only 3 types and variables have already been filtered.
          2
          # :nocov:
      end
    }
    
    is_tails << sorted_elements.any?{|element| element.is_a?(Tail) || element == UNKNOWN_TAIL }
    
    merged_value = sorted_elements.first
    
    if merged_value.is_a?(Tail) && merged_value.value.is_a?(Variable)
      UNKNOWN_TAIL
    else
      merged_value
    end
  }
  merged[0...-1] = merged[0...-1].map{|value|
    if value == UNKNOWN_TAIL
      nil
    else
      value
    end
  }
  
  merged = merged.map{|value|
    if is_tails.shift
      value
    else
      [value]
    end
  }
  merged = merged.flatten(1)
  merged = merged[0...fixed_length] if fixed_length
  
  [merged, unifications]
end

#unify_many_arrays(arrays, arrays_goals, visited = []) ⇒ Array<Array, Array>?

Attempt to unify multiple Arrays.

Parameters:

  • arrays (Array<Array>)

    the Arrays to be unified.

  • arrays_goals (Array<Porolog::Goal>)

    the Goals of the Arrays.

  • visited (Array) (defaults to: [])

    prevents infinite recursion.

Returns:

  • (Array<Array, Array>)

    the merged Array and the unifications to be instantiated.

  • (nil)

    if the Arrays cannot be unified.



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/porolog.rb', line 297

def unify_many_arrays(arrays, arrays_goals, visited = [])
  arrays_values = arrays.map{|array| expand_splat(array) }.map{|array| array.is_a?(Array) ? array.map{|element| element.value } : array.value }
  
  unless arrays_values.all?{|array_values| [:array,:variable].include?(array_values.type) }
    msg = "Cannot unify: #{arrays.map(&:inspect).join(' with ')}"
    arrays_goals.uniq.each{|goal| goal.log << msg }
    return nil
  end
  
  # TODO: Fix
  if arrays_values.size == 2 && arrays_values.any?{|array| array == UNKNOWN_ARRAY }
    merged = arrays_values.reject{|array| array == UNKNOWN_ARRAY }.first
    return [merged,[]]
  end
  
  number_of_arrays = arrays.size
  number_of_tails  = arrays.count{|array| has_tail?(array) }
  
  if number_of_tails == 0
    unify_arrays_with_no_tails(arrays, arrays_goals, visited)
  elsif number_of_tails == number_of_arrays
    unify_arrays_with_all_tails(arrays, arrays_goals, visited)
  else
    unify_arrays_with_some_tails(arrays, arrays_goals, visited)
  end
end

#unify_tail_with_tail(arrays, arrays_goals, visited) ⇒ Array<Array, Array>?

Unifies Arrays where each Array is not a Head/Tail array.

Parameters:

  • arrays (Array<Array>)

    the Arrays to be unified.

  • arrays_goals (Array<Porolog::Goal>)

    the Goals of the Arrays to be unified.

  • visited (Array)

    prevents infinite recursion.

Returns:

  • (Array<Array, Array>)

    the merged Array and the unifications to be instantiated.

  • (nil)

    if the Arrays cannot be unified.



580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
# File 'lib/porolog.rb', line 580

def unify_tail_with_tail(arrays, arrays_goals, visited)
  # -- Validate Arrays --
  unless arrays.map(&:headtail?).map(&:!).all?
    msg = "Wrong method called to unify #{arrays.inspect}"
    arrays_goals.uniq.each do |goal|
      goal.log << msg
    end
    return nil
  end
  
  # -- Variablise Arrays --
  arrays = arrays_goals.zip(arrays).map do |goal, array|
    goal.variablise(array)
  end
  
  # == [1,2,3]/:tail ~~ [1,2,3]/:tail ==
  # -- Extract Elements --
  merged       = []
  unifications = []
  
  arrays = arrays.sort_by{|array| -array.length }
  
  arrays[0].zip(*arrays[1..-1]).each_with_index do |values,index|
    if values.any?{|value| value.is_a?(Tail) }
      # -- Unify Remaining Values and Tails --
      tails = arrays.map{|array| expand_splat(array[index..-1]) }
      merged_tails = []
      tails.combination(2).each do |pair|
        next if pair.compact.size < 2
        if pair.any?{|tail| tail == UNKNOWN_ARRAY }
          merged_tails += pair.reject{|tail| tail == UNKNOWN_ARRAY }
          next
        end
        first_goal = nil
        last_goal  = nil
        first_goal = pair.first.goal if pair.first.respond_to?(:goal)
        last_goal  = pair.last.goal  if pair.last.respond_to?(:goal)
        m,u = unify_arrays(first_goal.variablise([pair.first]), last_goal.variablise([pair.last]), first_goal, last_goal, visited)
        unless m
          return nil
        end
        m[-1] = UNKNOWN_TAIL if m[-1] == nil
        merged_tails += m
        unifications += u
      end
      merged_tails.uniq!
      merged_tails_unifications = []
      # TODO: Fix [first_goal] * arrays.size
      if merged_tails.size > 1
        merged_tails, merged_tails_unifications = unify_many_arrays(merged_tails, [arrays_goals.first] * arrays.size, visited)
      end
      merged       += merged_tails.flatten(1)
      unifications += merged_tails_unifications - unifications
      break
    else
      # -- Unify Values at Index --
      merged_value = []
      values.combination(2).each do |pair|
        if pair.any?(&:nil?)
          merged_value += pair.compact
          next
        end
        first_goal = nil
        last_goal  = nil
        first_goal = pair.first.goal if pair.first.respond_to?(:goal)
        last_goal  = pair.last.goal  if pair.last.respond_to?(:goal)
        
        m,u = unify_arrays([pair.first], [pair.last], first_goal, last_goal, visited)
        if m.nil?
          [first_goal, last_goal].uniq.each do |goal|
            goal.log << "Cannot unify #{pair.first.inspect} with #{pair.last.inspect}"
          end
          return nil
        end
        merged_value += m
        unifications += u
      end
      merged << merged_value.compact.uniq.first || nil
    end
  end
  
  [merged, unifications]
end