logoalt Hacker News

galaxyLogictoday at 6:42 AM1 replyview on HN

I think a more interesting extension would be to see objects as functions. An object maps a set of keys to values. In most languages those keys must be strings. But I don't see why they couldn't be anything. For instance a key could be a function, and to access the value of such a key you would need to pass in exactly that function like this:

  let v = myObject [ myFunk ];
Like with arrays-as-functions, the domain of the object-as-function would be its existing keys. Or we could say the domain is any possible value, with the assumption that value of keys which are not stored in the object is always null.

Whether new keys could be added at runtime or not is a sepearate question.

It should be easy to extend the syntax so that

   myObject (anything) === myObject [anything]
whether myObject is an object, or a 'function' defined with traditional syntax.

Replies

lioeterstoday at 7:44 AM

Yes, we can look at an object as a function that accepts a key and returns a value (or null). Depends on language, it's called a set, map, or associative list.

  type AnObject = {
    [key: any]: any
  }

  type FunkyObject = (key: any) => Maybe<any>
Then we can see arrays as a limited type of object/function that only accepts a number (index) as key.

  type FunkyList = (index: number) => Maybe<any>
We can even consider any variable as a function whose key is the name.

  type FunkyVariable = (name: string) => Maybe<any>
And any operation as a function whose key is the operator, with arguments, and the return value is the result.

  type FunkyOperator = (name: string, ...values: any) => any

  FunkyOperator('+', 1, 2) // => 3
Even an `if` statement can be a function, as long as the values are functions that return values instead of the values themselves, to allow for "short-circuiting" (latter values are unevaluated if an earlier value is true).

So we approach some kind of functional language land where all data structures are modeled using functions.

show 1 reply