Powered by AppSignal & Oban Pro

Working with Objects

livebooks/working_with_objects.livemd

Working with Objects

System.put_env("AL_MNESIA_DISTRIBUTED", "false")

System.put_env(
  "AL_MNESIA_DIR",
  Path.join(System.tmp_dir!(), "al_livebook_#{:erlang.unique_integer([:positive])}")
)

Mix.install(
  [{:al, github: "anoma/AL-Ex"}],
  config: [al: [transaction_programs: [AL.TransactionProgram.Bootstrap], natives: []]]
)

Setup

This notebook is self-contained. The cell above installs AL directly, no separate node, no cookie, nothing to attach to. The first run compiles AL and its dependencies from scratch, which takes a minute or two. Reopening this notebook later is fast, since Mix.install caches by the exact dependency and config combination. State here is throwaway. It lives only for this notebook's session and disappears when the session ends.

If you already have a real AL node running and want the persistent, shared store instead, see the intro for how to attach to it instead.

Mix.install has to finish running before AL's macros (run, defclass, and the rest) can be brought into scope, so that happens in its own cell here.

use AL

AL.Branch.head()

Creating durable classes and instances

AL has an object system in the style of CLOS and Smalltalk, and aims to make writing live, open polymorphisms easy. The details of this will become more apparent later, but the basic ideas you need to know right now are that you can create classes with defclass, and instances of those classes with new. Let's try the well-known example of a light switch, which has on/off state.

We use the redef flag so that the class & instance can be redefined by re-evaluating the block. Inside :flick below you'll see get/set_slot, which read and write an object's own state. They're ordinary methods on :object, not special syntax, so get(obj, :key, value) is itself a message send, the same as flick(self) is.

run do
  defclass :switch,
    super: :object,
    redef: true,
    ivars: [%{name: :state, domain: ["on", "off"], default: "off"}] do

    defmethod(:flick, [self]) do
      get(self, :state, "on")
      set_slot(self, :state, "off")
    end
    
    defmethod(:flick, [self]) do
      get(self, :state, "off")
      set_slot(self, :state, "on")
    end
  end

  new(:switch, %{name: :switch_instance_1, state: "on", redef: true}, s)
end

In AL, durable objects are represented by atom IDs. You can inspect basic information about a durable object using examine/2.

run do
  examine(:switch_instance_1, info)
end
run do
  examine(:switch, info)
end

As you can see, :switch is a class which inherits from :object. It provides the method :flick, which we defined. It was used to create :switch_instance_1. :switches have a 'state' which is either on or off.

examine isn't the only way to see this. class/2 and super/2 are themselves ordinary queryable relations, not just something defclass declares once and hides away.

run do
  class(:switch_instance_1, c)
  super(:switch, s)
end

Let's see what happens if we 'flick' the 'switch'.

run do
  flick(:switch_instance_1)
  get(:switch_instance_1, :state, state)
end

It should work! And if you evaluate again, you'll see the state change too. flick(:switch_instance_1) is shorthand: it's exactly the same as writing the send out explicitly.

run do
  send(:switch_instance_1, :flick, [])
  get(:switch_instance_1, :state, state)
end

AL is also capable of enforcing slot invariants.

run do
  set_slot(:switch_instance_1, :state, :sideways)
end

Method dispatch

A send and label solve different problems. Dispatch decides which method can answer a message. It does not search for or construct every possible receiver.

For a ground receiver, AL dispatches a message like this:

  1. Determine the receiver's exact class. Lists, numbers, and maps have structural classes; durable objects have recorded classes; custom values carry their value class.
  2. Walk that class and its superclasses in method-resolution order.
  3. Select the nearest class that defines the selector. That provider owns the call; an overriding method does not silently fall through to an inherited provider when its clauses fail.
  4. Try that method's clauses by ordinary unification and backtracking.
  5. call_next_method explicitly continues with the next provider in the resolution order.

If the selected provider has no applicable clause, the send reaches does_not_understand. It does not silently try an inherited implementation.

For an open receiver, AL keeps the receiver symbolic:

  1. Find the classes and singleton objects that directly provide the selector.
  2. Create one logical branch for each possible effective provider.
  3. On a class branch, post both isa(receiver, provider) and the fact that this provider was selected for this selector.
  4. Run the method clauses relationally. Their heads and bodies can narrow the receiver further.
  5. Let later class, isa, slot, dif, and other constraints discard incompatible branches.

The provider regions are selector-relative. If :car overrides :move, the :vehicle branch for :move excludes cars, while a subclass that inherits :vehicle's implementation remains in the :vehicle branch. The receiver becomes concrete only if ordinary unification determines it or the program explicitly calls label.

Inheritance

As you may have already figured out, AL supports inheritance. This is not the scope to explain how inheritance itself works, but instead we will demonstrate a couple features that may be of benefit. For example, you can use call_next_method for method continuation and rely on inherited slots.

run dodefclass :counted_switch,
    redef: true,
    super: :switch,
    ivars: [%{name: :count, type: :number, default: 0}] do
    
    defmethod(:flick, [self]) do
      get(self, :count, c)
      c1 = c + 1
      set_slot(self, :count, c1)
      call_next_method(self)
    end
   end

  new(:counted_switch, %{name: :counted_switch_instance_1, redef: true}, c)
end
run doflick(:counted_switch_instance_1)
  examine(:counted_switch_instance_1, info)
end

In fact, AL even supports multiple inheritance. Let's take a look at the classic diamond inheritance problem. To demonstrate this, we'll need another kind of switch. Let's take one that flips its colour every time that it is turned on. For now we have a couple of limitations: Firstly, we must label the var, since constraints aren't durable in the database. Secondly, we don't have an ordering on the domain, meaning we can't express an exact cycle.

run do
  defclass :colour_cycle_switch,
    redef: true,
    super: :switch,
    ivars: [%{name: :colour, domain: ["red", "green", "blue"]}] do

    defmethod(:flick, [self]) do
      get(self, :state, "off")
      get(self, :colour, c)
      in_domain(c1, ["red", "green", "blue"])
      dif(c, c1)
      label(c1)
      set_slot(self, :colour, c1)
      call_next_method(self)
    end
    
    defmethod(:flick, [self]) do
      get(self, :state, "on")
      call_next_method(self)
    end
  end

  new(:colour_cycle_switch, %{name: :cc_switch_instance_1, colour: "red", redef: true}, c)
end
run do
  flick(:cc_switch_instance_1)
  examine(:cc_switch_instance_1, info)
end

Regardless this is sufficient for demonstrating how AL manages diamond inheritance. Here's a little tip: you can search a method by its object-associated name using the following snippet. For example:

run do
  findall([obj, id], objids) do
    method(obj, :flick, id)
  end
end
run do
  defclass :diamond_switch,
    redef: true,
    super: [:counted_switch, :colour_cycle_switch] do
  end

  new(:diamond_switch, %{name: :diamond_switch_instance_1, colour: "red", state: "off", redef: true}, c)
end

The order in which the two supers are topologically sorted actually doesn't matter for flick, since the operations we defined are commutative.

run do
  flick(:diamond_switch_instance_1)
  examine(:diamond_switch_instance_1, info)
end

Categories: importing methods without inheritance

categories: is a different way to share methods, and it isn't inheritance at all. A category is just an ordinary object with some methods on it. import copies those methods directly onto a class by their shared method id, with no super edge created — the class's own super chain is completely unaffected.

run do
  new(:category, %{name: :glowable, super: :object, ivars: []}, cat)

  defmethod(:glowable, :glow, [self, result]) do
    result = :shiny
  end

  defclass :lamp, super: :object, categories: [:glowable] do
  end

  new(:lamp, %{name: :lamp_1}, w)
  glow(:lamp_1, result)
end

:lamp answers :glow, but its super is still just :object.

run do
  super(:lamp, s)
end

Printing objects

Every object can describe itself for printing, through a relation called :print_object. It doesn't print anything by itself. It just relates self to some representation of it, and something else decides what to do with that (like listing below). The default version, defined on :object, just reports the object's own class.

run do
  print_object(:switch_instance_1, description)
end

Any class can override :print_object to describe its own instances better, the same way printOn: works in Smalltalk. We can add this straight to :switch without touching its existing :flick clauses, since defmethod also works as a standalone call, not only nested inside defclass.

run do
  defmethod(:switch, :print_object, [self, description]) do
    get(self, :state, s)
    description = {:switch, s}
  end

  print_object(:switch_instance_1, description)
end

vm_format (see syntax basics) has a directive for exactly this two-step dance. ~o resolves print_object on its argument automatically, then formats the result, so the cell above is the same as writing this in one step:

run do
  vm_format("~o~%", [:switch_instance_1])
end

Methods are printable objects too. :behaviour, the class every class, category and method eventually falls under, overrides :print_object to return a method's own source text instead of a class name. listing/2 uses that to print every clause of a method: give it a class and a method name, and it finds the method and runs print_object on each of its clauses.

run do
  listing(:switch, :flick)
end

Ephemeral Objects (Values)

So far we have only discussed 'durable' objects, without defining what this means. Each durable object in AL has a backing existence in the underlying Mnesia relation tables (which as you will see later, is just a RAM-based view over the command log).

Ephemeral/Value objects, on the other hand, only exist for the lifespan of a transaction, which means they do not clog up the database and are perfect for calculation. This means new objects can be generated 'on the fly' without dirtying the database.

A nice thing about ephemerals is that new gets to decide what the representation of an ephemeral actually is. In fact, numbers and lists are both ephemerals.

run do
  super(:number, :value)
end

We'll discuss the most interesting facets of ephemerals in logic and constraints.

Advanced: raw method dispatch

Everything so far has gone through ordinary dispatch: a send looks up which method answers a selector on a class, following its supers if it has to. vm_oapply skips inheritance chaining. You give it a method's own internal id directly, found with method, and it runs that exact method body, bypassing class/selector lookup entirely.

run do
  method(:number, :factorial, id)
  vm_oapply(id, [5, result])
end

This is how AL implements things like call_next_method under the hood. It is not advised to use this in ordinary code, although it may provide performance boosts since it does not require checking the inheritance chain.

Some philosophy on 'Relational Objects'

As you may have noticed, relations about objects don't require the object to 'exist' in some sense. In fact, to say that an object exists in AL is to say that there are relations which concern that object: The ID is meaningless in itself, and is just a handle or pointer to establish sameness- the essence of the object lies in its relations.