Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

objects as closures

by Excalibor (Pilgrim)
on Jul 07, 2003 at 15:07 UTC ( #271987=note: print w/replies, xml ) Need Help??

in reply to Re: (On Speed Diff, etc.) Closure on Closures (beta)
in thread Closure on Closures

And you should know, Abigail!!!

Actually, as Abigail just did (go quickly and grab Closures-1.2 in, you can construct a whole object system on top the closures (it's been done some dozen times in different ways in Scheme, where basically everything is a closure).

A simpler example, consider this code:

use strict; use warnings; sub Person { my %self = (); my @data = ( qw/name age/ ); my %mem = (); sub { for my $sub ( @data ) { $self{$sub} = sub { $mem{$sub} = $_[0] if @_; return $mem{$sub} } } return \&{$self{$_[0]}} if defined $self{$_[0]}; die "Method '$_[0]' unknown to class Person"; } }
We create a closure which exposes the interface of the class and holds both the methods (in %self) and data (in %mem, from memory). Please, note that it's impossible to read or write to the values held in %mem or %self (ie, modify the state of the object or modify its interface) directly, only through the interface exposed, which is very hygienic in itself. Using this is easy (if somewhat not very idiomatic):
# creating object my $john = Person; # initializing values $john->('name')->('John'); $john->('age')->(23); # working with object print "I'm ", $john->('name')->(), " and I am ", $john->('age')->(), " years-old, but my birthday is in just 2 seconds\n"; sleep( 2 ); $john->('age')->(24); print "Happy B-Day, ", $john->('name')->(), "!!!\n"; print "It's ", $john->('age')->(), " years-old already!!!\n"; print $john->('address')->(); __END__

Output is as expected (text between []'s is mine):

I'm John and I am 23 years-old, but my birthday is in just 2 seconds [two seconds pass...] Happy B-Day, John!!! It's 24 years-old already!!! Uncaught exception from user code: Method 'address' unknown to class Person at line 18 +. main::__ANON__('address') called at line 40

I am sure it's not too hard being able to force the dereference of the methods when you are on getter mode so instead of writing $john->('age')->() you can just say $john->('age') (as Abigail has in Closures-1.2). Probably an additional line checking the number of arguments passed to the method.

Except being the state held in the closures, this is all pure functional code; functional programming rules, yeah :)

best regards,

our $Perl6 is Fantastic;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://271987]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2018-07-19 11:50 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (406 votes). Check out past polls.