Showing posts with label functional. Show all posts
Showing posts with label functional. Show all posts

Sunday, May 29, 2011

Are Perl and Erlang functional enough for Nemo?

I have read interesting litmus test for a functional language from stackoverflow user Nemo. Just for curiosity there is mine try for perl:
sub Inc{1+shift}
sub Thrice {
  my $f=shift;
  sub {
    $f->($f->($f->(shift)))
  }
}
$\="\n";
  print
for Thrice(\&Inc)->(0),
    Thrice(Thrice(\&Inc))->(0),
    Thrice(\&Thrice)->(\&Inc)->(0)
and Erlang:
1> Thrice = fun(F) -> fun(X) -> F(F(F(X))) end end.
#Fun
2> Inc = fun(X) -> 1+X end.
#Fun
3> (Thrice(Inc))(0).
3
4> (Thrice(Thrice(Inc)))(0).
9
5> ((Thrice(Thrice))(Inc))(0).
27
Both seems functional enough for mine personal taste.

Tuesday, October 6, 2009

Closure vs. Object in Perl

I was curios how closures performs in comparison with objects in Perl. I have tested it on counter as the simplest possible abstraction with state.

use Benchmark qw(cmpthese);

sub make_counter {
    my $counter = shift;
    return sub { $counter++ };
}

package counter;

sub new {
    my ( $class, $counter ) = @_;
    return bless \$counter, $class;
}

sub inc { ${ shift() }++ }

package main;

our $inc = make_counter(1);

our $counter = counter->new(1);

cmpthese(
    -5,
    {   closure_make => q{make_counter(1)},
        object_make  => q{counter->new(1)}
    }
);

cmpthese(
    -5,
    {   closure => q{$main::inc->()},
        method  => q{$main::counter->inc()}
    }
);

And results are:

                 Rate closure_make  object_make
closure_make 420045/s           --         -35%
object_make  643969/s          53%           --
             Rate  method closure
method  2397172/s      --    -35%
closure 3697681/s     54%      --

Well, it is not simple. Both approaches have their benefits but if you want best performance and want little bit abstraction you should pass closure into your hot loop instead objects. But if you want create closure inside loop, than let you try avoid it or change to object. But you should not need it in hot loop anyway. I'm little bit surprised that closure construction is so expensive in perl. I have known that bless is not cheap operation, but closure?

Friday, February 1, 2008

Arc - mostly macros and syntactic sugar

Stefan Tilkov said about Arc:
After a quick glance at the tutorial, the most intriguing bit seems to be the support for macros, which work (almost) like function definitions. Interesting, but nothing that gets me overly excited.
I have same experinece. I read tutorial two days ago and I think it is mostly only scheme with macros and syntactic sugar. I am not so much familiar with lisp and scheme, but I think there is nothing what can't be done almost same simply in scheme or other lisp dialects. Updated: Steve dekorte think similar:
My own impression of Arc is that it's not significantly different from Scheme.