in reply to Programming Examples: Declarative, Imperative, Functional, Etc.

Something like this?
#!/usr/bin/perl use warnings; use strict; imperative(); procedural(); functional(); oo(); =head1 Various programming styles Pick a number between 1-10, and it tells you whether you guessed right + or not). =cut # IMPERATIVE ############################################ sub imperative { my $x = 1 + int rand 10; print 'Your guess? '; my $guess = <>; if ($guess == $x) { print "right\n"; } else { print "wrong\n"; } } # PROCEDURAL ############################################ sub procedural { my $x = generate(1, 10); my $guess = get_answer('Your guess?'); validate($x, $guess); } sub generate { my ($from, $to) = @_; return $from + int rand(1 + $to - $from); } sub get_answer { print @_, ' '; return scalar <>; } sub validate { my ($x, $guess) = @_; if ($guess == $x) { print "right\n"; } else { print "wrong\n"; } } # FUNCTIONAL ############################################ sub functional { validate(generate(1, 10), get_answer('Your guess?')); } # OO #################################################### { package Local::Guesser; sub new { bless {}, shift; } sub generate { my ($self, $from, $to) = @_; $self->{random} = $from + int rand(1 + $to - $from); } sub get_answer { my ($self, $prompt) = @_; print $prompt, ' '; $self->{answer} = <>; } sub validate { my $self = shift; if ($self->{random} == $self->{answer}) { print "right\n"; } else { print "wrong\n"; } } } sub oo { my $g = Local::Guesser->new; $g->generate(1, 10); $g->get_answer('Your guess?'); $g->validate; }
  • Comment on Re: Programming Examples: Declarative, Imperative, Functional, Etc.
  • Download Code

Replies are listed 'Best First'.
Re^2: Programming Examples: Declarative, Imperative, Functional, Etc.
by aaron_baugher (Curate) on Jul 27, 2012 at 15:30 UTC

    Thank you, those examples are very helpful. Now I'm wondering what category "chaining" of commands falls into, like this sort of thing in jQuery:

    $('#tag').first.parent.parent.addClass('new');

    Is that just functional programming written backwards?

    Aaron B.
    Available for small or large Perl jobs; see my home node.