�ߤ����Ȼפäƽ񤤤Ƥߤ���Ƴ������äȽ��褿�Τǡ�

Demo

�Ȥꤢ��������ʴ�����


Implementation

(function(){

var Lazy = function(a, f){
    for (var i = 0, l = a.length; i < l; i++) this[i] = a[i];
    this.length  = a.length;
    this.promise = f;
    this.defer   = [];
};

Lazy.prototype = [];
(function(o){
    for (p in o) Lazy.prototype[p] = o[p];
})({
    extend:function(n){
        if (!n) n = this.length;
        for (var i = this.length; i <= n; i++) this.push(this.promise(i));
        return this;
    },
    map:function(f){
        var that = new Lazy(this, this.promise);
        that.defer = Array.prototype.slice.apply(this.defer);
        that.defer.push(f);
        return that;
    },
    filter:function(f){
        var that = new Lazy(this, this.promise);
        that.defer = Array.prototype.slice.apply(this.defer);
        that.defer.push(function(e){ return f(e) ? e : null });
        return that;
    },
    take:function(n){
        if (n <= 0){
            return new Lazy([]);
        } else if (! this.defer.length){
            return new Lazy(this.extend(n-1).slice(0, n));
        }else{
            var ret = [], i = 0, e, j;
            loop: while (ret.length < n){
                e = this.extend(i)[i++];
                for (j = 0, l = this.defer.length; j < l; j++){
                    e = this.defer[j](e);
                    if (e === null) continue loop;
                }
                ret.push(e);
            }
            return new Lazy(ret);
        }
    },
    get:function(n){
        return this.take(n+1)[n];
    },
    toString:function(){
        return Array.prototype.slice.apply(this) + '';
    }
});

Array.Lazy = Lazy;

})();
  • ����Ū�ʹͤ���Tie::Array::Lazy��Ʊ���ǡ�­��ʤ����Ǥ����ä��餽���this.promise����Ͽ�����ؿ���������������碌�ޤ���
  • Tie::Array::Lazy�Ȱ�äƴ���Ʃ��Ǥʤ��Τϡ�this[n]��this.get(n)�ΰ㤤�ò¸«¤ï¿½Ð¤ï¿½ï¿½ï¤«ï¿½ê¤¤ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½Þ¤ï¿½ï¿½ï¿½Ruby�ߤ�����[]�������С��饤�ɲ�ǽ�ʥ᥽�åɤʤ餽�������ΤǤ�����
  • ���Ƥ��̤ꡢArray���ĥ��������äƤ���Τǡ����̤�Array�Ȥ��Ƥ�Ȥ��ޤ����ä�promise���ʤ����ο����ñ¤¤¤ï¿½Array�Ȥۤ�Ʊ���ΤϤ���Array�Ȱ㤦�Τϡ�Out of Bounds��undefined���֤������exception�ˤʤ뤳�ȡ�
  • ���ΤȤ����ٱ�ꥹ�Ȥ��������Τ�ɬ�פʥ᥽�åɤ�������ޤ���
  • �������ꡢmap��filter���ٱ�ɾ�����Ƥ��ޤ���
  • ;�̤Ǥ�����rakudo�Ǥ⤳�Υ�٥���ٱ�ɾ����ã������Ƥ��ޤ���
    > [0..Inf].grep({$^x % 2 == 0}).map({$^x+1})[10]
    21
    

Enjoy!

Dan the Lazy Evaluator