Resistance calculator: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (→‎{{header|Perl}}: subroutine signatures and code tweaks)
Line 571: Line 571:
===Infix===
===Infix===
{{trans|Raku}}
{{trans|Raku}}
<syntaxhighlight lang="perl">use strict;
<syntaxhighlight lang="perl">use v5.36;
use warnings;
use feature <say state>;


{
package Resistor;
package Resistor;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(set_voltage report);


use overload '+' => \&serial, '*' => \&parallel;
sub new {

my ($class, $args) = @_;
sub new ($class, $args) {
my $self = {
my $self = {
symbol => $args->{symbol},
symbol => $args->{symbol},
Line 590: Line 591:
}
}


sub res {
sub res ($self) {
my $self = shift;
if ($self->{symbol} eq '+') { return res($self->{a}) + res($self->{b}) }
if ($self->{symbol} eq '+') { return res($self->{a}) + res($self->{b}) }
elsif ($self->{symbol} eq '*') { return 1 / (1/res($self->{a}) + 1/res($self->{b})) }
elsif ($self->{symbol} eq '*') { return 1 / (1/res($self->{a}) + 1/res($self->{b})) }
else { return $self->{resistance} }
else { return $self->{resistance} }
}
}


sub set_voltage {
sub set_voltage ($self,$voltage) {
my($self,$voltage) = @_;
if ($self->{symbol} eq '+') {
if ($self->{symbol} eq '+') {
my $ra = res($self->{a});
my $ra = res($self->{a});
Line 611: Line 610:
}
}


sub current { my $self = shift; return $self->{voltage} / res($self) }
sub current ($self) { return $self->{voltage} / res($self) }
sub effect { my $self = shift; return $self->{voltage} * current($self) }
sub effect ($self) { return $self->{voltage} * current($self) }

use overload '+' => \&serial,
'*' => \&parallel;


sub serial { my($a,$b) = @_; Resistor->new( {symbol => '+', a => $a, b => $b} ) }
sub serial ($a,$b,$) { Resistor->new( {symbol => '+', a => $a, b => $b} ) }
sub parallel { my($a,$b) = @_; Resistor->new( {symbol => '*', a => $a, b => $b} ) }
sub parallel ($a,$b,$) { Resistor->new( {symbol => '*', a => $a, b => $b} ) }


sub report {
sub report ($self,$level = 0) {
my($self,$level) = @_;
state @results;
state @results;
push @results, ' Ohm Volt Ampere Watt Network tree' and $level = 1 unless $level;
push @results, ' Ohm Volt Ampere Watt Network tree' and $level = 1 unless $level;
Line 635: Line 630:


package main;
package main;
Resistor->import;


my ($R1, $R2, $R3, $R4, $R5, $R6, $R7, $R8, $R9, $R10) =
my ($R1, $R2, $R3, $R4, $R5, $R6, $R7, $R8, $R9, $R10) =
Line 642: Line 638:
* $R4 + $R3) * $R2 + $R1;
* $R4 + $R3) * $R2 + $R1;


Resistor::set_voltage($node,18);
set_voltage($node,18);
say Resistor::report($node);</syntaxhighlight>
say report($node);</syntaxhighlight>
{{out}}
{{out}}
<pre style="height:20ex"> Ohm Volt Ampere Watt Network tree
<pre> Ohm Volt Ampere Watt Network tree
10.000 18.000 1.800 32.400 | +
10.000 18.000 1.800 32.400 | +
4.000 7.200 1.800 12.960 | | *
4.000 7.200 1.800 12.960 | | *