Resistance calculator: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
SqrtNegInf (talk | contribs) m (→{{header|Perl}}: subroutine signatures and code tweaks) |
||
Line 571: | Line 571: | ||
===Infix=== |
===Infix=== |
||
{{trans|Raku}} |
{{trans|Raku}} |
||
<syntaxhighlight lang="perl">use |
<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); |
|||
⚫ | |||
sub new { |
|||
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 |
sub current ($self) { return $self->{voltage} / res($self) } |
||
sub effect |
sub effect ($self) { return $self->{voltage} * current($self) } |
||
⚫ | |||
'*' => \∥ |
|||
sub serial |
sub serial ($a,$b,$) { Resistor->new( {symbol => '+', a => $a, b => $b} ) } |
||
sub parallel |
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; |
||
set_voltage($node,18); |
|||
say |
say report($node);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre |
<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 | | * |