What's in a name?

As in all programming languages, KRL has reserved words and a certain structure, but also allows programmers to create their own names (or "identifiers") for various things.

As a perverse exercise, I recently created this ruleset with every possible identifier named name:

ruleset name {
  meta {
    shares __testing, name
  }
  global {
    __testing = { "queries":
      [ { "name": "__testing" }
      , { "name": "name", "args": [ "name" ] }
      ] , "events":
      [ { "domain": "name", "type": "name" }
      , { "domain": "name", "type": "name", "attrs": [ "name" ] }
      ]
    }
    name = function(name){
      name.klog("name") => name | "name"
    }
  }
  rule name {
    select when name name
    pre {
      name = event:attr("name").defaultsTo(name(name),"name")
    }
    send_directive("name",{"name": name || "name"})
  }
  rule name_provided {
    select when name name name re#(.+)# setting(name)
    send_directive("name",{"name": name})
  }
}

I then installed this ruleset in a pico named–you guessed it–name. Then, I did some experiments using the Testing tab, having turned on logging in the Logging tab. When it came time to enter a value to test the name:name event, I used, of course, "name" as that value.

There is a page, at picolabs.io/namename/ which shows the ruleset source code along with extracts from the Testing and Logging tabs, shown here:

You can hover your mouse over the occurrences of "name" and a tooltip will appear with a brief explanation and all related occurrences will also be highlighted.

For the most part, the various uses of name do not conflict. It is interesting, though, to consider the use of the global function named name in line 21, repeated here for convenience:

name = event:attr("name").defaultsTo(name(name),"name")

The function will be called, before the Universal Operator defaultsTo() is applied. At that point in time, the name name is bound to the global function, and so that function is called with itself as the argument! And, it will return itself as the result (because a function is considered "truthy"). When the event attribute named name is provided (i.e. is not null), defaultsTo() will not use it and will not produce output in the logs, but will just return the provided value. Notice that after this, the provided value will be bound to the name name. This shadows the name of the global function, which will no longer be available within this rule. Probably not a good practice.

Copyright Picolabs | Licensed under Creative Commons.