(blog ‘lucindo)

um dia eu aprendo a programar

Arquivo de Julho de 2007

Erlang Google Tech Talk

Sem comentários »

JavaScript…

Implementação do código do post sobre closures em JavaScript (com umas coisinhas a mais):

function cons(a, b) {
    return function(first) {
        return first ? a : b;
    }
}

function car(c) {
    return c(true);
}

function cdr(c) {
    return c(false);
}

function list() {
    arguments.shift = Array.prototype.shift;
    if (arguments.length == 0) {
        return null;
    } else {
        return cons(arguments.shift(), list.apply(this, arguments));
    }
}

function mapcar(fun, lst) {
    if (null == lst) {
        return null;
    } else {
        return cons(fun(car(lst)), mapcar(fun, cdr(lst)));
    }
}

function reduce(fun, init, lst) {
    if (null == lst) {
        return init;
    } else {
        return fun(car(lst), reduce(fun, init, cdr(lst)));
    }
}

function filter(fun, lst) {
    if (null == lst) {
        return null;
    } else {
        if (fun(car(lst))) {
            return cons(car(lst), filter(fun, cdr(lst)));
        } else {
            return filter(fun, cdr(lst));
        }
    }
}

Um teste tosto:

var lst = list(1, 2, 3, 4);
mapcar(print, lst);
print(reduce(function (a, b) { return a + b; }, 0, lst));
mapcar(print, filter(function (a) { return a % 2; }, lst));

Para rodar, usei o Rhino.

1 comentário »

Lisp Hacks

Link com algumas coisas legais: Lisp hacks.

Um dos possíveis hacks é a memoização de funções. Fiz um pequeno teste:

CL-USER(1): (requireasdf-install)
…
CL-USER(2): (asdf-install:install :memoize)
…
CL-USER(3): (defun fib (n)
              (if (< n 2)
                  n
                  (+ (fib (- n 1))
                     (fib (- n 2)))))
FIB
CL-USER(4): (time (fib 42))

Evaluation took:
  21.129 seconds of real time
  21.04396 seconds of user run time
  0.025874 seconds of system run time
  0 calls to %EVAL
  0 page faults and
  0 bytes consed.
267914296
CL-USER(5): (compile ‘fib)

FIB
NIL
NIL
CL-USER(6): (time (fib 42))

Evaluation took:
  20.074 seconds of real time
  19.975544 seconds of user run time
  0.03109 seconds of system run time
  0 calls to %EVAL
  0 page faults and
  0 bytes consed.
267914296
CL-USER(7): (memoize:memoize-function ‘fib)

FIB
CL-USER(8): (time (fib 42))

Evaluation took:
  0.0 seconds of real time
  7.1e-5 seconds of user run time
  2.e-6 seconds of system run time
  0 calls to %EVAL
  0 page faults and
  8,136 bytes consed.
267914296
Sem comentários »

Steve Jobs Stanford Commencement Speech 2005

Sem comentários »