Skip to content

Instantly share code, notes, and snippets.

@librasteve
Last active July 16, 2023 10:34
Show Gist options
  • Save librasteve/4a1bd7cbb94f9c9e8d47229555cc469e to your computer and use it in GitHub Desktop.
Save librasteve/4a1bd7cbb94f9c9e8d47229555cc469e to your computer and use it in GitHub Desktop.
raku in procedural, functional and OO style comparison
#`[ procedural stylee
my @people = [ %( name => 'Mary', height => 160 ),
%( name => 'Isla', height => 80 ),
%( name => 'Sam', ), ];
my $height-total = 0;
my $height-count = 0;
for @people -> %person {
if %person<height> {
$height-total += %person<height>;
$height-count += 1;
}
}
if $height-count {
my $average-height = $height-total / $height-count;
say $average-height
}
#]
#`[ functional stylee
my \people = ( ( name => 'Mary', height => 160 ).Map,
( name => 'Isla', height => 80 ).Map,
( name => 'Sam', ).Map, );
my \heights = people.grep( *<height> ).map( *<height> );
if heights.elems {
my \average-height = ( [+] heights ) / heights.elems;
say average-height
}
#]
#`[ oo stylee
class Person {
has Str $.name is required;
has Real $.height;
}
class Group {
has Person @.people;
method heights( --> Seq ) {
@.people.grep( *.height ).map( *.height )
}
method average-height( --> Real ) {
my @h := @.heights;
( [+] @h ) / @h if @h
}
}
my @people = ( Person.new( name => 'Mary', height => 160 ),
Person.new( name => 'Isla', height => 80 ),
Person.new( name => 'Sam', ), );
my $group = Group.new( :@people );
say $group.average-height;
#]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment