Search code examples
objectinstancefactor-lang

Why not an `instance?` word?


Many object-aware scripting languages have an operator or function to test if an object is an instantiation of a given tuple or type. JavaScript has the instanceof operator, Python has an isinstance builtin as well as an issubclass builtin, etc.

But in Factor, all tuple classes and object types are given their own instance? word:

TUPLE: car speed ;
! autogenerated is the word car?, which tests if something is a car
TUPLE: boat weight ; 
! autogenerated is the word boat?, which tests if something is a boat
100 boat boa boat? ! -> t
100 boat boa car?  ! -> f

Boats are boats and cars are cars. Cars are not boats.

We could rephrase the last two lines like:

100 boat boa boat instance-of? ! -> t
100 boat boa car  instance-of? ! -> f

Instead, every object in Factor has its own specialised instance? word. Is this just for brevity and readability, or is there an implementation reason?

Would one want to customise the instance? word on certain objects for some reason? We have generics for that...


Solution

  • Your instance-of? would work most of the time:

    : instance-of? ( obj cls -- ? ) [ class-of ] dip class<= ;
    123 boat boa boat instance-of? .
    t
    123 boat boa tuple instance-of? .
    t
    123 fixnum instance-of? . 
    t
    

    But it is not good enough for more complicated types:

    QUALIFIED: math.primes 
    PREDICATE: even < integer 2 mod 0 = ;    
    PREDICATE: prime < integer math.primes:prime? ;
    7 prime? .
    t
    6 even?
    t
    7 prime instance-of?
    f
    6 even instance-of? .
    f
    

    The other reason is optimization. Words like fixnum?, string? and array? that are used in performance sensitive code are much easier to make fast than a more general instance-of? word.