reperiendi

Reading list

Posted in Category theory, Math, Programming by Mike Stay on 2008 April 28

Great synesthesia FAQ

Posted in Perception by Mike Stay on 2008 April 3

Objects (in the OOP sense) as lambda terms

Posted in Programming by Mike Stay on 2008 April 2

Consider some javascripty pseudocode:

  aPoint = {x:3, y:4};

This is an object that responds to four messages: “x”, “x =”, “y”, “y =”

  >> aPoint.x
  [ {x:3, y:4}, 3 ]

  >>  aPoint.y
  [ {x:3, y:4}, 4 ]

  >> aPoint.x = 15
  [ {x:15, y:4}, null ]

  >> aPoint.x
  [ {x:15, y:4}, 15 ]

An object consists of code and state, and responds to messages; in the process of responding to a message, the object can change its state. In essence, an object is a function

  obj:STATE x MESSAGE x INPUT \to STATE x OUTPUT

except that objects provide encapsulation: the internal state of the object is never directly accessible; the only way to see or change the state of an object is through the object’s response to messages. So we define an object to be a lambda term of the form

  Y ((self, state, message, input) \mapsto [
      self(new_state(state, message, input)),
      result(state, message, input)
    ]) (initial_state)

where ‘Y’ is the fixpoint combinator, the notation (x \mapsto y) is an alternative notation for \lambda x.y, brackets [-, -] denote a pair, and the terms ‘new_state’ and ‘result’ evaluate to objects on all terminating inputs.

Let makePoint be the term

  Y ((self, state, message, input) \mapsto [
      self( 
          if (message == "x =") then [ input, state(1) ] else
          if (message == "y =") then [ state(0), input ] else
          state),
      if (message == "x") then state(0) else
      if (message == "y") then state(1) else
      null
    ]).

Then aPoint = makePoint([ 3, 4 ]) =

  (message, input) \mapsto [
      makePoint(
          if (message == "x =") then [ input, 4 ] else
          if (message == "y =") then [ 3, input ] else
          [ 3, 4 ]),
      if (message == "x") then 3 else
      if (message == "y") then 4 else
      null
    ].