Should I choose a hash, an object or an array to represent a data instance in Perl? - arrays

I was always wondering about this, but never really looked thoroughly into it.
The situation is like this: I have a relatively large set of data instances. Each instance has the same set or properties, e.g:
# a child instance
name
age
height
weight
hair_color
favorite_color
list_of_hobbies
Usually I would represent a child as a hash and keep all children together in a hash of hashes (or an array of hashes).
What always bothered me with this approach is that I don't really use the fact that all children (inner hashes) have the same structure. It seems like it might be wasteful memory-wise if the data is really large, so if every inner hash is stored from scratch it seems that the names of the key names can take far more sapce than the data itself...
Also note that when I build such data structures I often nstore them to disk.
I wonder if creating a child object makes more sense in that perspective, even though I don't really need OO. Will it be more compact? Will it be faster to query?
Or perhaps representing each child as an array makes sense? e.g.:
my ($name, $age, $height, $weight, $hair_color, $favorite_color, $list_of_hobbies) = 0..7;
my $children_h = {
James => ["James", 12, 1.62, 73, "dark brown", "blue", ["playing football", "eating ice-cream"]],
Norah => [...],
Billy => [...]
};
print "James height is $children_h->{James}[$height]\n";
Recall my main concerns are space efficiency (RAM or disk when stored), time efficiency (i.e. loading a stored data-set then getting the value of property x from instance y) and ... convenience (code readability etc.).
Thanks!

Perl is smart enough to share keys among hashes. If you have 100,000 hashes with the same five keys, perl stores those five strings once, and references to them a hundred thousand times. Worrying about the space efficiency is not worth your time.
Hash-based objects are the most common kind and the easiest to work with, so you should use them unless you have a damn good reason not to.
You should save yourself a lot of trouble, start using Moose, and stop worrying about the internals of your objects (although, just between you and me, Moose objects are hash-based unless you use special extensions to make them otherwise -- and once again, you shouldn't do that without a really good reason.)

I guess it is mainly personal taste (except of course when other people have to work on your code too)
Anyway, I think you should look into moose It is definitely not the most time nor space efficient, but it is the most pleasant and most secure way of working.
(By secure, I mean that other people that use your object can't misuse it as easily)
I personally prefer an object when I'm really representing something.
And when I work with objects in perl, I prefer moose
Gr,
ldx

Unless absolute speed tuning is a requirement, I would make an object using Moose. For pure speed, use constant indexes and an array.
I like objects because they reduce the mental effort needed to work with big deep structures. For example, if you build a data structure to represent the various classrooms in a school. You'll have something like a list of kids, a teacher and a room number. If you have everything in a big structure you have to know the structure internals access the hobbies of the children in the classroom. With objects, you can do somthing like:
my #all_hobbies = uniq map $_->all_hobbies,
map $_->all_students, $school->all_classrooms;
I don't care about the internals. And I can concisely generate a unique list of all the kids hobbies. All the complicated accesses are still happening, but I don't need to worry about what is happening. I can simply use the interface.
Here's a Moose version of your child class. I set up the hobbies attribute to use the array trait, so we get a bunch of methods simply for the asking.
package Child;
use Moose;
has [ 'name', 'hair_color', 'fav_color' ] => (
is => 'ro',
isa => 'Str',
required => 1,
);
has [ 'age', 'height', 'weight' ] => (
is => 'ro',
isa => 'Num',
required => 1,
);
has hobbies => (
is => 'ro',
isa => 'Int',
default => sub {[]},
traits => ['Array'],
handles => {
has_no_hobbies => 'is_empty',
num_hobbies => 'count',
has_hobbies => 'count',
add_hobby => 'push',
clear_hobbies => 'clear',
all_hobbies => 'elements',
},
);
# Good to do these, see moose best practices manual.
__PACKAGE__->meta->make_immutable;
no Moose;
Now to use the Child class:
use List::MoreUtils qw( zip );
# Bit of messing about to make array based child data into objects;
#attributes = qw( name age height weight hair_color fav_color hobbies );
my #children = map Child->new( %$_ ),
map { zip #attributes, #$_ },
["James", 12, 1.62, 73, "dark brown", "blue", ["playing football", "eating ice-cream"]],
["Norah", 13, 1.75, 81, "black", "red", ["computer programming"]],
["Billy", 11, 1.31, 63, "red", "green", ["reading", "drawing"]],
;
# Now index by name:
my %children_by_name = map { $_->name, $_ } #children;
# Here we get kids with hobbies and print them.
for my $c ( grep $_->has_hobbies, #children ) {
my $n = $c->name;
my $h = join ", ", $c->all_hobbies;
print "$n likes $h\n";
}

I usually start with a hash and manipulate that, until I find instances where the data I really want is derived from the data that I have. And/or that I want some sort of peculiar--or even polymorphic--behavior.
At that point, I start creating a packages to store class behavior, implementing methods as needed.
Another case is where I think this data would be useful in more than one instance. In that case, it's either rewrite all the selection cases everywhere where you think you'll need it or package the behavior in a class, so that you don't have to do too much copying or studying of the cases the next time you want to use that data.

Generally, if you don't need utter efficiency, hashes will be your best bet. In Perl an object is just a $something with a class name attached. The object can be a hash, an array, a scalar, a code reference, or even a glob reference inside. So objects can only possibly be a win in convenience, not efficiency.
If you want to give an array a shot, the typical way of making that somewhat maintainable is using constants for the field names:
use strict;
use warnings;
use constant {
NAME => 0,
AGE => 1,
HEIGHT => 2,
WEIGHT => 3,
HAIR_COLOR => 4,
FAVORITE_COLOR => 5,
LIST_OF_HOBBIES => 6,
};
my $struct = ["James", 12, 1.62, 73, "dark brown", "blue", ["playing football", "eating ice-cream"]];
# And then access it with the constants as index:
print $struct->[NAME], "\n";
$struct->[AGE]++; # happy birthday!
Alternatively, you could try whether using an array (object) as follows makes more sense:
package MyStruct;
use strict;
use warnings;
use Class::XSAccessor::Array
accessors => {
name => 0,
age => 1,
height => 2,
weight => 3,
hair_color => 4,
favorite_color => 5,
list_of_hobbies => 6,
};
sub new {
my $class = shift;
return bless([#_] => $class);
}
package main;
my $s = MyStruct->new;
$s->name("James");
$s->age(12);
$s->height(1.62);
$s->weight(73);
# ... you get the drill, but take care: The following is fine:
$s->list_of_hobbies(["foo", "bar"]);
# This can produce action-at-a-distance:
my $hobbies = ["foo", "bar"];
$s->list_of_hobbies($hobbies);
$hobbies->[1] = "baz"; # $s changed, too (due to reference)
Coming back to my original point: Usually, you want hashes or hash-based objects.

Whenever I try to decide between using a hash or an array to store data, I almost always use a hash. I can almost always find a useful way to index the values in the list for quick lookup. However, your question is more about hashes of array refs vs hashes of hash refs vs hashes of object refs.
In your example above, I would have used a hash of hash refs rather than a hash of array refs. The only time I would use an array is when there is an inherent order in the data that should be maintained, that way I can look things up in order. In this case, there isn't really any inherent order in the arrays you're storing (e.g., you arbitrarily chose height before weight), so it would be more appropriate (in my humble opinion) to store the data as a hash where the keys are descriptions of the data you're storing (name, height, weight, etc).
As to whether you should use a hash of hash refs or a hash of object refs, that can often be a matter of preference. There is some overhead associated with object-oriented Perl, so I try only to use it when I can get a large benefit in, say, usability. I usually only use objects/classes when there are actions inherently associated with the data (so I can write $my_obj->fix(); rather than fix($my_obj);). If you're just storing data, I would say stick with a hash.
There should not be a significant difference in RAM usage or in time to read from/write to disk. In terms of readability, I think you will get a huge benefit using hashes over arrays, since with the hashes the keys actually make sense, but the arrays are just indexed by numbers that have no real relationship with the data. This may require more disk space for storage if you're storing in plain text, but if that's a huge concern you can always compress the data!

Related

Array destructuring in Ruby

I've got a variable data which comes in one of the following two formats:
[1,2,3]
[[1,2,3],['a','b','c']]
At some point I need to parse this data and so I do:
main, alternative = data
While case (2) works as expected, (1) doesn't.
Instead it sets:
main=1
alternative=2
# 3 is dropped.
My end goal however is this:
main=[1,2,3]
alternative=nil
What's the most elegant way to do this? Ideally I'd like to avoid conditionals and long methods...
My honest answer here is don't pass data around in a fuzzy, poorly-defined structure. If at all possible, improve the underlying caller to send consistently-defined objects.
However if you're looking for a quick patch, then how about:
# data comes in one of the following two formats:
# 1. [1,2,3]
# 2. [[1,2,3],['a','b','c']]
# So, this patch enforces some consistency in the structure:
data = [data, nil] unless data.first.is_a?(Array)
main, alternative = data
If you are lucky enough to be running on ruby 2.7 or 3, you can use pattern matching:
case data
in [Array => main, Array => alternative]
# here `main` and `alternative` are bound to the expected items
# because the match succeeds by type.
in main
# now main is bound but alternative might still be bound to the previous
# clause, so don't use it.
alternative = nil
end
A more fluent, but still correct, way would be
data in [Array => main, Array => alternative] or data in Array => main
# now main and alternative are as expected
If the structure (length) of the array is known beforehand to be 3, you might also be comfortable with
data in [[_,_,_] => main, [_,_,_] => alternative] or data in [_,_,_] => main
so you have less false negatives.

In Perl 6, can I use an Array as a Hash key?

In the Hash documentation, the section on Object keys seems to imply that you can use any type as a Hash key as long as you indicate but I am having trouble when trying to use an array as the key:
> my %h{Array};
{}
> %h{[1,2]} = [3,4];
Type check failed in binding to parameter 'key'; expected Array but got Int (1)
in block <unit> at <unknown file> line 1
Is it possible to do this?
The [1,2] inside the %h{[1,2]} = [3,4] is interpreted as a slice. So it tries to assign %h{1} and %{2}. And since the key must be an Array, that does not typecheck well. Which is what the error message is telling you.
If you itemize the array, it "does" work:
my %h{Array};
%h{ $[1,2] } = [3,4];
say %h.perl; # (my Any %{Array} = ([1, 2]) => $[3, 4])
However, that probably does not get what you want, because:
say %h{ $[1,2] }; # (Any)
That's because object hashes use the value of the .WHICH method as the key in the underlying array.
say [1,2].WHICH; say [1,2].WHICH;
# Array|140324137953800
# Array|140324137962312
Note that the .WHICH values for those seemingly identical arrays are different.
That's because Arrays are mutable. As Lists can be, so that's not really going to work.
So what are you trying to achieve? If the order of the values in the array is not important, you can probably use Sets as keys:
say [1,2].Set.WHICH; say [1,2].Set.WHICH
# Set|AEA2F4CA275C3FE01D5709F416F895F283302FA2
# Set|AEA2F4CA275C3FE01D5709F416F895F283302FA2
Note that these two .WHICHes are the same. So you could maybe write this as:
my %h{Set};
dd %h{ (1,2).Set } = (3,4); # $(3, 4)
dd %h; # (my Any %{Set} = ((2,1).Set) => $(3, 4))
Hope this clarifies things. More info at: https://docs.raku.org/routine/WHICH
If you are really only interested in use of an Object Hash for some reason, refer to Liz's answer here and especially the answers to, and comments on, a similar earlier question.
The (final1) focus of this answer is a simple way to use an Array like [1,'abc',[3/4,Mu,["more",5e6],9.9],"It's {<sunny rainy>.pick} today"] as a regular string hash key.
The basic principle is use of .perl to approximate an immutable "value type" array until such time as there is a canonical immutable Positional type with a more robust value type .WHICH.
A simple way to use an array as a hash key
my %hash;
%hash{ [1,2,3].perl } = 'foo';
say %hash{ [1,2,3].perl }; # displays 'foo'
.perl converts its argument to a string of Perl 6 code that's a literal version of that argument.
say [1,2,3].perl; # displays '[1, 2, 3]'
Note how spaces have been added but that doesn't matter.
This isn't a perfect solution. You'll obviously get broken results if you mutate the array between key accesses. Less obviously you'll get broken results corresponding to any limitations or bugs in .perl:
say [my %foo{Array},42].perl; # displays '[(my Any %{Array}), 42]'
1 This is, hopefully, the end of my final final answer to your question. See my earlier 10th (!!) version of this answer for discussion of the alternative of using prefix ~ to achieve a more limited but similar effect and/or to try make some sense of my exchange with Liz in the comments below.

using ruby to extract the values in a hash in a DRY way

My app passes to different methods a json_element for which the keys are different, and sometimes empty.
To handle it, I have been hard-coding the extraction with the following sample code:
def act_on_ruby_tag(json_element)
begin
# logger.progname = __method__
logger.debug json_element
code = json_element['CODE']['$'] unless json_element['CODE'].nil?
predicate = json_element['PREDICATE']['$'] unless json_element['PREDICATE'].nil?
replace = json_element['REPLACE-KEY']['$'] unless json_element['REPLACE-KEY'].nil?
hash = json_element['HASH']['$'] unless json_element['HASH'].nil?
I would like to eliminate hardcoding the values, and not quite sure how.
I started to think through it as follows:
keys = json_element.keys
keys.each do |k|
set_key = k.downcase
instance_variable_set("#" + set_key, json_element[k]['$']) unless json_element[k].nil?
end
And then use #code for example in the rest of the method.
I was going to try to turn into a method and then replace all this hardcoded code.
But I wasn't entirely sure if this is a good path.
It's almost always better to return a hash structure from a method where you have things like { code: ... } rather than setting arbitrary instance variables. If you return them in a consistent container, it's easier for callers to deal with delivering that to the right location, storing it for later, or picking out what they want and discarding the rest.
It's also a good idea to try and break up one big, clunky step with a series of smaller, lighter operations. This makes the code a lot easier to follow:
def extract(json)
json.reject do |k, v|
v.nil?
end.map do |k, v|
[ k.downcase, v['$'] ]
end.to_h
end
Then you get this:
extract(
'TEST' => { '$' => 'value' },
'CODE' => { '$' => 'code' },
'NULL' => nil
)
# => {"test"=>"value", "code"=>"code"}
If you want to persist this whole thing as an instance variable, that's a fairly typical pattern, but it will have a predictable name that's not at the mercy of whatever arbitrary JSON document you're consuming.
An alternative is to hard-code the keys in a constant like:
KEYS = %w[ CODE PREDICATE ... ]
Then use that instead, or one step further, define that in a YAML or JSON file you can read-in for configuration purposes. It really depends on how often these will change, and what sort of expectations you have about the irregularity of the input.
This is a slightly more terse way to do what your original code does.
code, predicate, replace, hash = json_element.values_at *%w{
CODE PREDICATE REPLACE-KEY HASH
}.map { |x| x.fetch("$", nil) if x }

Storing values in hash of array more effectively

I'm working on a script that generates large hash of arrays (HoAs) data structures. I'm trying to optimize my script because currently it's taking forever to run.
Recently I read from a site that one way you can further improve the speed of your script execution is to use a subroutine to store values in say a hash of arrays. It said it's especially great for large data structures.
Here's the example the article gave.
sub build_hash{
# takes 3 params: hashref, name, and value
return if not $_[2];
push(#{ $_[0]->{'names'} }, $_[1]);
push(#{ $_[0]->{'value'} }, $_[2]);
# return a reference to the hash (smaller than making copy)
return $_[0];
}
The article said calling this subroutine to build the HoA is 40% faster than pushing values onto the hash of array outside of the subroutine. The subroutine is supposedly fast because it builds the data structure using references.
I would like to test this subroutine out by building my own HoA. Say I wanted to create the following hash of arrays.
%HoA = (
'C1' => ['1', '3', '3', '3'],
'C2' => ['3','2'],
'C3' => ['1','3','3','4','5','5'],
'C4' => ['3','3','4'],
'C5' => ['1'],
);
How would I implement build_hash to do this? Also, how would I call this subroutine?
Here's what I have but it's not quite working.
# let AoA be an array of arrays that contains the values I want to assign
# to each key in %HoA
my #AoA = (
['1', '3', '3', '3'],
['3','2'],
['1','3','3','4','5','5'],
['3','3','4'],
['1']
);
my %HoA;
my $count = 1;
foreach my $ref (#AoA){
build_hash(\%HoA, $ref, "C$count");
$count++;
}
sub build_hash {
# takes 3 params: hashref, arrayref, and key
return if not $_[2];
push(#{ $_[0]->{$_[1]} }, $_[2]);
# return reference to HoA_ref (smaller than making copy)
return $_[0];
}
I'm glad you liked my presentation, but I think the point of that slide didn't come across without the talk that went with it. I was trying to show how directly accessing #_ instead of copying the contents into local variables can save a bit of time on a very frequently called and otherwise minimal sub.
It's unlikely that building the HoA is really the slow part of your program. I would advise you to do what I did before making the change shown in my slide, which is to run Devel::NYTProf on your program and see where the time is going. Then you'll know what needs to be fixed.
my %HoA; $HoA{"C$_"} = $AoA[$_-1] for 1..#AoA;
or
my %HoA; #HoA{ map "C$_", 1..#AoA } = #AoA;
or
my %HoA = map { "C$_" => $AoA[$_-1] } 1..#AoA;
Sorted from fastest to slowest (I think), but they're roughly all as fast as the other.
That is not what those slides say at all. What Perrin is showing is a way to reduce the sub call overhead assuming you need to have the subroutine at all, because calling a subroutine takes time. You aren't going to make code faster by adding subroutines where they're not needed.

"merge" two arrays and iterate through the new array in Rails

Let's say I have
#colors = #product.colors.all
#storages = Storage.all
I need to loop through all combinations for these two and create an entry in a different model
How to tell the app to run this call for each color,storage and assign corresponding ids?
Stock.find_or_create_by_product_id(:product_id => #id, :color_id => XXX, :storage_id => XXX)
I've got a secret for you: Ruby has documentation. There are lots of really awesome methods that are hidden from the bad developers that you can use to look awesome to your co-workers and they're all revealed to those in the know in the documentation. For example, Array#product is a really awesome method that will take another array as an argument and return an array with every combination of those two arrays (matter of fact, it'll take an unlimited number of arrays and return all combinations of all of the arrays). Pretty cool, right?
Here's how you might use it to make your situation easier:
#colors = #product.colors.all
#storages = Storage.all
#colors.product(#storages).each do |color, storage|
Stock.find_or_create_by_product_id(:product_id => #id, :color_id => color.id, :storage_id => storage.id)
end
Welcome to the secret club. :)

Resources