6

I was curious about grammars being classes or singletons, so I created this small program to find out:

grammar Mini {
    token TOP { \* <word> \* }
    token word { \w+ }
}

proto sub is-class( | ) { * };
multi sub is-class( Grammar:D $g ) { return "Object" };
multi sub is-class( Grammar:U $g ) { return "Class" };

say is-class( Mini );

This uses multiple dispatch to find that out, and it turns out that Mini is actually a class. In general, would there be a shorter way of finding this out? Or a way that would not require to know the actual class of which the package might be an instance?

jjmerelo
  • 22,578
  • 8
  • 40
  • 86
  • 1
    FYI. While Perl culture is very tolerant of words being used just as regular general language words without regard for technical definitions I'd like to note that the word [Container](https://docs.perl6.org/language/containers) has a technical meaning in P6 and a grammar isn't a container in that technical sense. The generic technical term for units such as `grammar`s, `class`es, `role`s, `module`s and `package`s is [Package](https://docs.perl6.org/language/packages). – raiph Oct 17 '18 at 11:55
  • I'll change that. Thanks. – jjmerelo Oct 17 '18 at 14:07
  • 1
    `say is-class( Mini.new )` ⇒ `Object` – Brad Gilbert Oct 17 '18 at 19:37

1 Answers1

7

You can disambiguate 'instances' and 'classes' via DEFINITE, ie

Mini.DEFINITE ?? 'Object' !! 'Class'

or rather

Mini.DEFINITE ?? 'concrete object' !! 'type object'

should do the trick.

Christoph
  • 164,997
  • 36
  • 182
  • 240
  • 2
    .oO ( or, in keeping with `:D` and `:U`, `Mini.DEFINITE ?? 'Definite instance' !! 'Universal concept'` ) – raiph Oct 09 '18 at 13:44
  • I would think that `.defined` would be preferable in most cases, though. For example, `Failure` objects are never `.defined` but can bed `.DEFINITE` and for most use-cases you want to stick to that difference. https://stackoverflow.com/questions/48986414/whats-the-difference-between-perl-6s-definite-and-defined-methods – zostay Oct 15 '18 at 21:55