I watched an MIT lecture on youtube demonstrating some of the abstraction power of LISP. Then I tried my hand at duplicating the functionality in Perl. Below I will post the LISP code, and the Perl equivalent.
LISP
(DEFINE (SUM TERM A NEXT B)
(IF (> A B)
0
(+ (TERM A)
(SUM TERM
(NEXT A)
NEXT
B))))
(DEFINE (SUM-INT A B)
(DEFINE (IDENTITY X) X)
(SUM INDENTITY A 1+ B))
(DEFINE (SUM-SQ A B)
(SUM SQUARE A 1+ B))
(DEFINE (SQUARE A) (* A A))
(SUM-INT 3 5)
(SUM-SQ 3 5)
Perl
#!/usr/bin/perl
use warnings;
use strict;
use feature "state";
sub sum # TERM A NEXT B
{
state $sum;
my ($TERM, $A, $NEXT, $B) = @_;
if ($A>$B){
my $temp=$sum;
$sum=0;
return $temp ;
}
$sum+=&{$TERM}($A);
sum( $TERM, &{$NEXT}($A) ,$NEXT, $B);
}
sub identity{
shift;
}
sub square{
((shift)**2);
}
sub sumint { sum(\&identity,shift,sub {((shift)+1)},shift)}
sub sumsq { sum(\&square,shift,sub {((shift)+1)},shift)}
#a normal sum from 3-5
print sumint(3,5) . "\n";
#a sum of squares from 3-5
print sumsq(3,5) . "\n";
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|