Wednesday 3 December 2014

arithmetic

Next up, arithmetic. Now, note BKO is not designed to be a general purpose programming language. There are zillions of those! BKO is aimed at the knowledge-representation/AI niche.

The point is, we can do arithmetic, but it is ugly. The python now, and a couple of examples (fact and fib) in the next post. Not super happy with this code, but it does the job, and it was from way back when I was still in the early stages of learning python.
# the arithmetic function
# eg: arithmetic(|number: 3>,|symbol: +>,|number: 8>)
#
def arithmetic(x,operator,y):
  x_label = x if type(x) == str else x.the_label()
  op_label = operator if type(operator) == str else operator.the_label()
  y_label = y if type(y) == str else y.the_label()

  cat1, v1 = extract_category_value(x_label)
  name, op = extract_category_value(op_label)
  cat2, v2 = extract_category_value(y_label)
  if cat1 != cat2 or op not in ['+','-','*','/','%','^']:
    return ket("")
  try:
    x = int(v1)
    y = int(v2)
  except ValueError:
    try:
      x = float(v1)
      y = float(v2)
    except ValueError:
      return ket("")
  label = ""
  if len(cat1) > 0:
    label = cat1 + ": "      
  if op == '+':
    return ket(label + str(x + y))
  elif op == '-':
    return ket(label + str(x - y))
  elif op == '*':
    return ket(label + str(x * y))
  elif op == '/':
    if y == 0:         # prevent div by zero
      return ket("",0)
    return ket(label + str(x / y))
  elif op == '%':
    return ket(label + str(x % y))
  elif op == '^':
    return ket(label + str(x ** y))
  else:
    return ket("")   # presumably this should never be reached. 
I guess a couple of things to note:
1) the |> wrapping around everything is a tad ugly in this case. But we must stick to every object being either a ket or a superposition, otherwise we break our model.
2) heh, the "amplification factor" of this function versus the python "answer = a*b" is huge!

And I guess that is it. I'll put it to use in the next post.

Update: note that the arithmetic function returns |> if the categories/data-types do not match. This is to prevent errors where you mix data-types. eg, say adding pounds and kilos.

Update: the standard solution to arithmetic on kets you are not 100% sure of the data-type is something like this:
arithmetic(to-km |x>,|+>,to-km |y>)
which gives an answer in km, assuming |x> and |y> support the to-km operator, independent of the actual type of x and y.

No comments:

Post a Comment