[icon] 9
View:Recent Entries.
View:Archive.
View:Friends.
View:User Info.
Фильтр френдов:Online Friends. Коммунити.
Мой жж:Tags.
You're looking at the latest 8 entries.

Tags:,
Subject:The java vs k screencast in ruby… in javascript
Time:11:45 pm
Number.prototype.rand = function() {
  return Math.floor(Math.random()*this+1);
}
Number.prototype.to = function(to) {
    var array = [Number(this)];
    if (this < to) for (var i = this + 1; i <= to; ++i)    array.push(i);
    else for (var i = this - 1; i >= to; --i)    array.push(i);
    return array;
}
Number.prototype.times = function(callback) {
  if (typeof callback == 'string') callback = new Function('i', callback);
  for (var i = 0; i < this; i++) callback(i)
}

Array.prototype.map = Array.prototype.forEach = function(callback, thisObject) {
  if (typeof callback == 'string') callback = new Function('el', 'i', 'array', 'return ' + callback);
  var array = [];
  for (var i = 0, len = this.length; i < len; ++i)
    array.push(callback.call(thisObject, this[i], i, this));
  return array;
}
Array.prototype.filter = function(pred, thisObject) {
  if (typeof pred== 'string') pred= new Function('el', 'i', 'array', 'return ' + pred);
  var array = [];
  for (var i = 0, len = this.length, ret; i < len; ++i)
   if (pred.call(thisObject, this[i], i, this))
     array.push(this[i]);
  return array;
}
Array.prototype.foldRight = function(proc, seed) {
  for (var i = this.length - 1; i >= 0; --i) seed = proc.call(null, this[i], seed);
  return seed;
}
Array.prototype.deleteItem = function(item, eq, thisObject) {
  if (!eq) eq = function(x, y) { return x == y } 
    return this.remove(function(y) { return eq.call(null, item, y) }, thisObject);
}
Array.prototype.remove = function(pred, thisObject) {
  var array = [];
  for (var i = 0, len = this.length, ret; i < len; ++i)
    if (!pred.call(thisObject, this[i], i, this)) array.push(this[i]);
  return array;
}
Array.prototype.uniq = function(eq, thisObject) {
  return this.foldRight(function(item, array) { return [item].concat(array.deleteItem(item, eq, thisObject)) }, []);
}
people = 10;
days = 356;
bdays = 1 .to(people).map('days.rand()');
alert(bdays); // 151,264,286,135,17,34,266,108,135,274

collision = function(a) {
  return a.length != a.uniq().length;
}
alert(collision(bdays)); // true

collided = 0;

1000 .times("if ( collision(1 .to(people).map('days.rand()')) ) collided++");
alert(collided); // 112

alert(0 .to(1000).map("collision(1 .to(people).map('days.rand()'))")); 
// false, false, false, false, false, false, false, false, true, false, false, ...
alert(0 .to(1000).map("collision(1 .to(people).map('days.rand()'))").filter("!!el").length); // 110 alert(0 .to(1000).map("collision(1 .to(23).map('days.rand()'))").filter("!!el").length); // 499 alert(0 .to(1000).map("collision(1 .to(25).map('days.rand()'))").filter("!!el").length); // 570
Хотя в этом и нет смысла, но на javascript тоже можно так делать))
comments: 4 comments or Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:[PHP] функциональный стиль…
Time:12:55 pm
Еще даже не начав изучать php, и даже не изучив ни одного функционального языка программирования {кроме яваскрипта)))}. Я, наверное, даже не очень-то разбираюсь в том, что же такое этот функциональный стиль программирования. Тем не менее, я заинтересовался: «а в php map да reduce есть?»

Оказалось, что в нем есть функции array_map, array_reduce… Хорошо. Потом оказалось, что можно туда даже анонимную функцию запихнуть через create_functional, но такой код уж совсем нельзя назвать простым, красивым, понятным, элегантным.

Нашел одинокое сообщение в форуме xpoint, которое, к сожалению, сейчас доступно только через кеш яндекса:

Работа с данными массивов

Господа! Вопрос о рационализации.
Чтобы каждый элемент массива, допустим, обрамить тэгами <B> в языке Perl возможна следующая конструкция:

@my_arr=map("<B>$_</B>", @my_arr);

В PHP тоже есть array_map() — но ИМХО это слишком громоздко добавлять целую функцию:

function add_b($e){
  return "<B>$e</B>";
}

$my_arr=array_map("add_b", $my_arr);

Можно еще привлечь циклы, но тоже сложновато: приходится вводить две новые переменные:

foreach($my_arr as $key=>$value)
  $my_arr[$key]="<B>$value</B>"

А попроще/покрасивее никак?

Тогда я решил поискать ссылки в делишез. Ввел /tag/functional+php {когда-то я нашел в делишез очень много интересного, посвященному функциональному программированию на яваскрипте — особое внимание стоит уделять ссылкам на японском, т.к. там куча вкусного}

Делишез на этот запрос выдал много всего. Бегло пробежав по первым ссылкам я остановился на статье Functional PHP: this time it works. Автор вводит функцию map:
function map($chunk, $sequence) {
  $output = array();
  foreach ($sequence as $_2 => $_1) 
    $output[] = eval($chunk);
  return $output;
}
Что же… тогда получается можно написать так:
$my_arr=map('return "<b>$_1</b>";', $my_arr);
Правда, я не знаю, работает ли оно. Но кода стало явно меньше)))
comments: 3 comments or Leave a comment Add to Memories Tell a Friend

Tags:,
Current Music:Bjцrk & Brodsky Quartet — Cowboy Lemmings
Subject:send("hello").to("Pasha");
Time:01:24 pm
send = function(msg)
{
  return {
    to: function(name){
      alert('"' + msg + '" to "' + name + '"');
    }
  }
}

send("hello").to("Pasha"); // "hello" to "Pasha"
PS. «Изобрел велосипед», блин)))

javascript 
functional 
comments: 6 comments or Leave a comment Add to Memories Tell a Friend

Tags:, ,
Time:10:25 pm
Итак, надо из двумерного массива с данными получить табличку.
var data = 
  [
    [null, 'name1', ['Р.', 'Бах']],
    [null, 'name2', ['В.', 'Бах']],
    [null, 'name3', ['Л.', 'Баг']],
    [null, 'name4', ['Р.', 'Бах']],  
  ];
#nameauthor
1name1Р. Бах
2name2В. Бах
3name3Л. Баг
4name4Р. Бах
Read more... )
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:99 bottles of beer
Time:09:29 am
Haskell:
bottles 0 = "no more bottles"
bottles 1 = "1 bottle"
bottles n = show n ++ " bottles"
verse 0   = "No more bottles of beer on the wall, no more bottles of beer.\n"
         ++ "Go to the store and buy some more, 99 bottles of beer on the wall."
verse n   = bottles n ++ " of beer on the wall, " ++ bottles n ++ " of beer.\n"
         ++ "Take one down and pass it around, " ++ bottles (n-1)
                                                 ++ " of beer on the wall.\n"
main      = mapM (putStrLn . verse) [99,98..0]
JavaScript:
bottles = FunctionMaker(n);
bottles(0).eq("'no more bottles'");
bottles(1).eq("'1 bottle'");
bottles(n).eq("n + ' bottles'");

verse = FunctionMaker(n);
verse(0).eq(function(){
  return "No more bottles of beer on the wall, no more bottles of beer.\n"+
    "Go to the store and buy some more, 99 bottles of beer on the wall."
});
verse(n).eq(function(n){
  return bottles(n) + " of beer on the wall, " + bottles(n) + " of beer.\n"+
    "Take one down and pass it around, " + bottles(n-1) + 
    " of beer on the wall.\n"
});

var count = 5;
var i     = count+1;

while (--i+1) p(verse(i))
Пример на яваскрипте проверять на сайте like a haskell — web λ.0 javascript Read more... )
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Current Music:Skafandr — [Globalizm - Instrumental music of St.Petersburg
Subject:like a haskell — web λ.0 javascript
Time:11:24 pm
fib = FunctionMaker(n);
fib(0).eq(1);
fib(1).eq(1);
fib(n).eq("fib(n-2)+fib(n-1)");
p(fib(10));
// dump memoized value
p(fib.memo.toJSON())
result:
89
{
 "0" : 1,
 "1" : 1,
 "2" : 2,
 "3" : 3,
 "4" : 5,
 "5" : 8,
 "6" : 13,
 "7" : 21,
 "8" : 34,
 "9" : 55,
 "10" : 89
}
like a haskell — web λ.0 javascript
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Time:11:26 am
Higher-Order JavaScript англ. — A JavaScriptish companion to Mark-Jason Dominus's Higher-Order Perl http://hop.perl.plover.com/

Связанные ссылки:
Higher Order Perl (and Javascript / Ruby)
comments: Leave a comment Add to Memories Tell a Friend

Tags:, ,
Subject:Functional_Javascript
Time:08:13 pm
comments: Leave a comment Add to Memories Tell a Friend

[icon] 9
View:Recent Entries.
View:Archive.
View:Friends.
View:User Info.
Фильтр френдов:Online Friends. Коммунити.
Мой жж:Tags.
You're looking at the latest 8 entries.