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";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: PERLISP meditations
by moritz (Cardinal) on Sep 29, 2012 at 13:33 UTC | |
by protist (Monk) on Sep 29, 2012 at 13:39 UTC | |
|
Re: PERLISP meditations
by LanX (Saint) on Sep 29, 2012 at 14:24 UTC | |
by protist (Monk) on Sep 29, 2012 at 15:03 UTC | |
by LanX (Saint) on Sep 29, 2012 at 15:14 UTC | |
by protist (Monk) on Sep 29, 2012 at 15:46 UTC | |
|
Re: PERLISP meditations
by remiah (Hermit) on Oct 03, 2012 at 22:25 UTC |