📜 ⬆️ ⬇️

Features (traits) in Perl 6 - metadata along with a symbol

Features (Traits) is a convenient and extensible way to attach metadata to various kinds of objects in Perl 6. Consider an example of a feature with is cached that automatically caches the return value of a function depending on the arguments passed.

#   ,    #  'is cached' multi sub trait_mod:<is>(Routine $r, :$cached!) { my %cache; #    ,  $r.wrap(-> $arg { #     %cache{$arg}:exists ?? %cache{$arg} # ...   ,     !! (%cache{$arg} = callwith($arg)) } ); } #  : sub fib($x) is cached { say("fib($x)"); $x <= 1 ?? 1 !! fib($x - 1) + fib($x - 2); } #     0  10      say fib(10); 


The feature applies with the verb, in this case - is. It is indicated in the name of the function that handles the feature, here - trait_mod :. The arguments to the handler are the object to which the feature is applied, and the name of the feature (cached) as the named argument.

In our example, the function's .wrap method is called, but you can, of course, call anything. This is usually used to include roles in a function or add them to a distribution table.
')
Features can be applied not only with functions - but also with parameters, attributes, and variables. For example, accessors with write access are implemented through the rw feature:

  class Book { has @.pages is rw; ... } 

Also features are used to attach documentation to classes and attributes, mark the parameters of functions as rewritable, and declare inheritance classes and apply roles to them.

Source: https://habr.com/ru/post/271711/


All Articles