ときどきの雑記帖 混迷編

最新ページへのリンク
目次ページへのリンク

一つ前へ 2011年3月(下旬)
一つ後へ 2011年4月(中旬)

ホームへ

2011年04月10日

■_

・ボールペン
LAMY【ラミー】 ボールペン pico(ピコ) L284 プラチナコート
LAMY【ラミー】 ボールペン pico(ピコ) L284 プラチナコート
わたしが使ってるのは実はこの色じゃないんですが、これしかなかったので:) いろいろと携帯用のボールペンを試してきましたが、これで決まりという感じです。 値段が高いのがちと難点ですが、安くて(といいつつも1000円くらいはする)も すぐにダメになるとか不満がでるよりはいいと思います。

どんなのを試してきたのか全部アサマシ貼り付けたいところなんですが、 メーカーやら思い出したり調べたりするのが面倒なのでそれは止めます。 よく手帳と一緒にあるようなものだと、軸が細くて書きにくいのと、 先の円錐形になってるところがすぐに取れちゃうんですよね。 使い方が悪いといわれればそうなのかもしれませんけど。 ほかにも、この LAMY Pico のように普段は格納形式で使うときに伸ばすタイプのも 二つ三つ試しましたが、そのうちひとつはポケットに放り込んでたらいつのまにか微妙に変形して 伸ばしたり縮めたりがとても困難に。 残ったのも書き味やらで比べると…

・TAPL読書会
昨日聞き忘れたこと。 9.4 The Curry-Howard Correspondence てところに、 いろいろ議論が沸き起こりました。とあり、 さらに数名の名前と西暦年(多分論文の年?)が書かれていたのですが、 一番古いものでも1989年、2000年あたりまであって、 ずいぶんと最近の話だったのだなあと思ったのですけど よーく考えてみると、1989年って22年も前じゃん… ○| ̄|_

■_ あなたも今すぐ試せるプロうグラマーの生産性のための三つのtips

a dime a dozen…5010セント硬貨12枚?

3 programmer productivity tips you can try right now - driven by improvement
3 programmer productivity tips you can try right now

Productivity tips are a dime a dozen, but I really wanted to share these 3 which have 
been kind of useful to me (real world useful).

生産性についてのtips はとてもありふれたことですが、わたしにとって有用であった
三つを共有したいと心から思っています。

I haven't invented any of them, just put together from things I've read.

わたしがそれらのtipsを発明したわけではなく、読んだことのあるものをただ単にまとめただけです。

Although magically simple, each of these tips can have a tremendous impact on your daily
output, your procrastination habits and your overall mood!

ここに挙げた tips のそれぞれはびっくりするほど単純なものですが、あなたの日々の
アウトプット (your daily output)、procrastination (ぐずぐずすること) habits(習慣)、
気分全体に対して素晴らしいインパクトをもたらすかもしれません。


Take a look at each of them, and think about how they could apply to what you're doing right now:

    * Eat the Frog First
    * Set a Date
    * Visualize


Eat the Frog First
最初にカエルを食べる

    If you eat a frog first thing in the morning that will probably be the worst thing 
    you do all day. - Mark Twain 

If you start your day with the thing you least want to do, or the thing you've been putting
off the most, you'll get a feeling of accomplishment that will stay with you for the rest of
the day.

一日をあなたがもっともやる気が起こらないものだったり止めてしまいたいものから始めてしまえば、
その日の残りは


Do the hard stuff first, and you'll feel empowered!
大変なことを最初にやろう。そうすれば

Set a Date

Try to clearly define a date and time slot for your most important tasks.
最も重要なタスクのdate and time slot を明確に定義することを試みましょう。

This tip is actually worth two:
この tip は実際には二つの worth があります:

    * setting a date to get something done works a lot better than just putting more 
      stuff into your ToDo list;
      ただ単にToDoリストに入れるよりもずっと良く仕事をこなすために日付を設定します

    * and deciding how much time you are going to spend on a task makes you focus on 
      what is really important to get the job done.
      そしてどのくらい時間をかけるのかを決めます


Visualize
可視化

Next time you try to do something, first imagine doing it in your mind.
次に何かをしようとするときには、どのようにするのかということを最初に想像してみましょう。

Be as detailed as possible, imagine all the finer points of the work you're doing.

可能な限り詳細に、あなたが行おうとしている仕事のすべての finer points を想像しましょう。

Imagine the problems you would have, imagine how you would go around them. Imagine the 
feeling of sucess at the end of a job well done.

あなたが遭遇するであろう問題を想像しましょう。
それをどのように回避するのかを想像しましょう。
仕事を首尾良く終えたときの feeling of success を想像しましょう。

That way, when you actually do the thing, it will be a lot like doing the thing for 
the second time: free experience, just using your prefrontal cortex

■_ ++

まあ += 1 でもあればいいとは思うんだけど(さすがに同じ変数名二回は書きたくない)。

Ruby 初心者スレッド Part 41

794 デフォルトの名無しさん [sage] 2011/04/10(日) 06:42:01.76 ID: Be:
    いやいや、i++で1増えるほうが気持ち悪いから。
    ってかこれこれ誰が考えたんだよ。
    C言語作った奴か? 

795 デフォルトの名無しさん [sage] 2011/04/10(日) 07:02:40.24 ID: Be:
    まあオブジェクト指向が机上の空論か学者のオモチャだったころのイケてるフィーチャーだったものなので
    現在のRubyのようにイテレータがきちんと枚挙をサポートしてれば出番は確実に減る 

796 デフォルトの名無しさん [sage] 2011/04/10(日) 07:36:51.42 ID: Be:
    i++はC++からだったと思う 

797 デフォルトの名無しさん [] 2011/04/10(日) 08:39:36.13 ID: Be:
    i++ はCが考案されたときPDP-11のアセンブラ命令にそのまま落とせて便利じゃね?
    と思って作られたもの。

798 デフォルトの名無しさん [sage] 2011/04/10(日) 09:03:51.43 ID: Be:
    うそつくな。B言語にあるじゃないか。
    http://cm.bell-labs.com/cm/cs/who/dmr/kbman.html 

799 デフォルトの名無しさん [sage] 2011/04/10(日) 09:15:30.57 ID: Be:
    http://cm.bell-labs.com/cm/cs/who/dmr/chist.html

    > Thompson went a step further by inventing the ++ and -- operators, [...].
    > They were not in the earliest versions of B, but appeared along the way.

    訳)ケンは大きいつづらを、リッチーは小さなつづらを選びました。
    すると中には黄金虫が 

800 デフォルトの名無しさん [] 2011/04/10(日) 10:35:35.16 ID: Be:
    Cの次はPといううわさが大昔にあったな。

■_

■_ R

R のソースに、Windows 流のコードページやら locale の名称と、 UNIX 流のそれとの対応とるようなコードがあるんですが、 自分もそういうのを作ってたり。 っても何年か前に途中まで作って(xgawk で使った)放置してるんですが。

src/extra/win_iconv/win_iconv.c
/*
 * iconv library implemented with Win32 API.
 *
 * This file is placed in the public domain.
 *
 * Maintainer: Yukihiro Nakadaira <yukihiro.nakadaira  gmail.com>
 *
 * Win32 API does not support strict encoding conversion for some
 * codepage.  And MLang function drop or replace invalid bytes and does
 * not return useful error status as iconv.  This implementation cannot
 * be used for encoding validation purpose.
 */

/* Primary source is apparently
  http://code.google.com/p/win-iconv/source/checkout

  This version is from http://www.gtk.org/download-windows.html
 */

そうそう。コード変換もいろいろ面倒があったのだった。

■_

知力体力時の運

2011年04月09日

■_

・TAPL読書会
基礎体力(知識)がないので、毎回頭を酷使してます(^^; 今回はすでにきちんとまとめられているのでそちらに(手抜き)→ TAPL読書会@東京 第5回開催記録 - kencobaの日記 TAPL 読書会 第 5 回 - Elliptium ま、月に一度くらいはこれぐらい頭を使うことをしておかないと。

・買ったのとかまだ買えてないのとか
エリック・エヴァンスのドメイン駆動設計 (IT Architects’Archive ソフトウェア開発の実践) 良いコードを書く技術 -読みやすく保守しやすいプログラミング作法 (WEB+DB PRESS plus)
この二冊が土曜日に買った(買えた)分。 ここ数日、献本されたとかいうツイートを見て以下略な気持ちになったのは内緒だ:)
こっちの二冊は書店で見つけられなくてまだ買ってない(けどアサマシは貼っておこう)。 Perl CPANモジュールガイド Rパッケージガイドブック

そいや、TAPL読書会中に圏論の話題で盛り上がり、いろいろと参考図書の名前が出たりしたんですが そのうちの一冊
Categorical Logic and Type Theory, Volume 141 (Studies in Logic and the Foundations of Mathematics)
これ、買ってたと思ったら買ってなかった。 確か、一万円切ってたときに教えてもらったのだけど 油断してたら一万円超えちゃってそのまま放置してたような記憶がかすかに。 今からでも買っておくべきか ○| ̄|_ (この本も読書会があるのでね)

■_ ネタ

2ちゃん某板某スレッドにて。


664 メロン名無しさん [sage] 2011/04/09(土) 13:20:56.84 ID:???0 Be:
    優勝しそうなときだけベイスターズを応援するような
    そんなあざといマネができるかよ! 苦楽をともにしてこそだろ!
    って佐藤藍子が
    >>597,598 

この話、よーーーく覚えてるけど、 1998年(ベイスターズ優勝の年)って何年前だよ(^^;

■_ atoi(らしきもの)

reddit で盛り上がっていたのでリンクをたどるとこんなコード片が。

Not Naming Any Names – Small Thoughts

He was told to write atoi

A good friend of mine from the University of Waterloo just send me a code snippet he 
had saved up. This is a very remarkable piece of code. The background to the code was 
that it was written during the operating systems course (Computer Engineering) and 
that one of his group members was asked to write an aoti function in C for the OS. 
Here's what he e-mailed back:

	INT16 atoi_convert (CHAR * input)
	{
	    UINT16 output = 0 ;
	    CHAR * a;
	    while (a == "input++")
	    {
	      output = output*10 + (a -'0');
	     return output ;
	    }
	    return output;
	}

    It's impressive that it compiles.


まあ。「エラーにはならない」わなあ。

He was asked to write atoi()...I can't believe it compiles. : programming

The compiler optimized version of this function:

INT16 atoi_convert (CHAR * input)
{
    return 0;
}


This trolled me, I thought it was supposed to work because of some miracle of dangling 
pointers really representing something real, but it's just as garbage as it appears:)

That may well be the case; as ever, which languages you should be looking at depends 
on what you are doing, and you may not be doing work that C is suited to.

Agreed. I guess it makes sense when you need to worry more about performance and 
optimization than is normally necessary.

You are judging by looking at highly optimized code. In most languages, such code is 
not possible to write. If you want code that looks better, you can stay in C or C++, 
just write some classes to do the same thing. Fast performing micro-code is usually 
hard to follow since it necessitates writing for the complier, and C is the only one 
that allows it.

■_ APLのような

K言語とか。 kevinlawler/kona - GitHub

Kona | Lambda the Ultimate

Kona

Kona is a new open-source implementation of Arthur Whitney's K, an ASCII-based APL 
like language. Kona is a fully working version of K3.

If you haven't ever tried APL/J/K or ilk you might find this language incomprehensible 
at first -- unless you like a challenge! Watch the screencasts or read some of our 
earlier APL/J stories.

Regardless of your interest in K, any LtUer worth his salt will enjoy the source code. 
We wrote a bit about the history of the remarkable C coding style used in the past, 
but I can't locate the link at the moment.

■_ The Programming Language with the Happiest Users

「最も幸福なユーザーを持ったプログラミング言語」。あたり?

The Programming Language with the Happiest Users | The CrowdFlower Blog

The Programming Language with the Happiest Users

May 12th, 2009 by Lukas Biewald

Which languages make programmers the happiest? It's clear that some languages are 
more popular than others, and many of us debate long and hard over the relative merits 
of Python vs Ruby, C vs Java or Lisp vs everything else. But what's the general 
consensus?

プログラマーを最も幸福にするのはどの言語でしょうか?
一部の言語がそのほかの言語よりもずっと popular であることは明白です。
また、わたしたちの多くが Python vs Ruby や C vs Java、Lisp vs その他すべて
のようなものについて、その相対的なメリットを飽きることなく討論しています。
#ちと意訳しすぎ?
しかし、general consensus とはどういったものでしょうか?

I decided to do a little market research. I scraped the top 150 most recent tweets on 
Twitter for the query “X language” where X was one of {COBOL, Ruby, Fortran, Python, 
Visual Basic, Perl, Java, Haskell, Lisp, C}.

わたしはそのためにちょっとした市場調査をすることにしました。
“X 言語”という query での Twitter 上の直近 150 個のツイートを集めたのです。
ここで、X は COBOL、Ruby、Fortran、Python、Visual Basic、Perl、Java、Haskell、
Lisp、C のいずれかが入ります。

(略)

On the other hand, many tweets are very clear, such as, Once again I find myself 
battling with Haskell. Why oh why create such a language? or The more I learn about 
Haskell, the more impressed I am with the language. Nothing like intentional infinite 
recursion, mind = blown.

Without further ado, here are the results:

答えは元ページで! :) The Programming Language with the Happiest Users | The CrowdFlower Blog

■_ 行きたい

縁はなさそうだけどさあ○| ̄|_ >ませまちか

O'Reilly Village/オラの村 - 『Mathematicaクックブック』刊行記念セミナー 書泉ブックタワーにて開催

"エバンジェリストたちが語るMathematicaの魅力と可能性"

Mathematicaの威力と魅力を伝える意欲作『Mathematicaクックブック』の発刊を記念し、秋葉原
の書泉ブックタワー(9F イベントフロア)にてセミナーを開催いたします。 翻訳者の松田裕幸
氏が、本書に掲載されている事例を取り上げ、Mathematicaの魅力と威力について熱く語ります。
また、本書は、原書・翻訳書ともにMathematicaノートブックを使って組版されました。この経
験を踏まえ、出版におけるノートブックの可能性と今後の役割について、編集にご協力いただい
た大橋真也氏にお話しいただきます。 さらにスペシャルゲストとしてMathematica開発元のウル
フラムリサーチさんをお出迎えし、Mathematica最新版の新機能についてご紹介して頂きます。
Mathematicaの魅力と最新情報に触れる絶好の機会です!是非お誘い合わせの上、ご来場くださ
い。

■_

2011年04月08日

■_

やる気ゼロ♪

■_ R

いろいろぐぐる先生に訊いたりなんだりしてどうにかできそうな気配。

#include <stdio.h>
#include <locale.h>
#include <fcntl.h>
int
main()
{
    char *msgs[] = {
        /* " と      入      力      す      れ      ば" */
        "\x82\xC6\x93\xFC\x97\xCD\x82\xB7\x82\xEA\x82\xCE\n",
        "\x82",
        "\xc6",
        "\x93",
        "\xfc",
        "\x97",
        "\xcd",
        "\x82",
        "\xb7",
        "\x82",
        "\xea",
        "\x82",
        "\xce\n",
        NULL
    };
    char **p;

    _setmode(_fileno(stdout), _O_BINARY); /*+++*/
    setlocale(LC_ALL, ""); /*!!!*/
    for (p=msgs; *p; p++) {
        printf("%s", *p);
        fflush(stdout);
    }

    return 0;
}

標準出力をテキストモードからバイナリモードにしてやると、 文字コード変換で悪さしなくなるので期待通りに出るようになる。らしい。 バイナリモードにすると、改行とかどうすんのよという気がするのですが なんかそれっぽく出ているような。 いずれにしても、rterm.exe でやってみてどうかを確かめないと。

■_

住めば都のコスモス荘がDVD-BOX かあ。持ってるけど買う気がががが

海の向こうで Commodore 64 てのなら、日本では… PC-8001? (異論が相当でそうだ)

■_

TAPL読書会で見たような式が。

Question about "Practical Foundations of Programming Languages" : haskell

I don't know if there would be a better place to ask, but I've started reading Robert 
Harper's Practical Foundations of Programming Languages and I've not even finished the 
first chapter that I'm a little stumped. In 1.6, he defines the sum(a; b; c) 
relationship as such:

1.6 で著者は sum(a; b; c) の関係 (relationship) を次のように定義しています:

    b nat
---------------
sum(zero; b; b)


     sum(a; b; c)
------------------------
sum(succ(a); b; succ(c))

I'm not sure how to read this, and how to understand it. This is what I got right now: 
"If b is a natural, then the sum of zero and b is b" and "if c is the 
sum of a and b, then succ(c) is the sum of succ(a) and b".

Say I wanted to prove that sum(succ(zero), succ(zero), succ(succ(zero))), how would I 
do that? I take my expression and consider it the conclusion of a rule, find the 
premise, keep going until I reach the b nat case in which case I check that b = c?

Thank you for your help, and sorry if this is off topic.

回答? 編は省略。

■_ Language popularity absurdity

TIOBE index の結果を馬鹿正直に受け止めちゃだめよというおはなし。

Language popularity absurdity « Accidentalidad
Language popularity absurdity

Looking at April's TIOBE index for language popularity, it got even more absurd. As 
they write: “Other interesting moves in the TIOBE index this month can be found 
outside the top 20. This is due to the fact that the index uses 7 different search 
engines as of this month.”

言語の popularity を示すTIOBE index の四月の結果を見てみると、とてもお話にならない
ものになっています。彼らが、
「今月の TIOBE index の興味深い結果が20位以下ののに見られます。これは七つの異なる
検索エンジンを今月は使った index だからです」と書いたように。

As a result, many languages have dropped out the 20 to 50 range, Groovy and Scala are 
two examples. And some surprising items entered. While I have better things to do than 
to analyse their search procedure, two simple indicators show how ridiculous this 
index has become:

その結果、多くの言語が20位~50位圏から外れました。Groovy や Scala はその例です。


    * Progress 4GL : TIOBE position 45 – Google for “Progress 4GL programming language”: 10,400 results (“4GL programming language” 42,000 results) – not listed on Github

    * TOM : TIOBE position 49 – Google for “TOM programming language” : 21,500 results – not listed on Github

    * SIGNAL : TIOBE position 50 – Google for “SIGNAL programming language” : 194,000 results – not listed on Github

In comparison:

    * Scala : TIOBE position > 50 – Google for “Scala programming language” : 739,000 results – Github position #17

    * Groovy : TIOBE position > 50 – Google for “Groovy programming language” : 39,100 results – Github position #22

This is an index about popularity, right? Well maybe the results are distorted by 
searching over all time. Let's search in google with a restriction to posts within 
the last year:

これが本当に popularity の指標 (index) なんでしょうか?


    * “4GL programming language” – 124 results
    * “TOM programming language” – 59 results
    * “SIGNAL programming language” – 870 results
    * “Scala programming language” – 45,000 results
    * “Groovy programming language” – 644 results

Ooops. Conclusion: The TIOBE index is a complete joke, and it's sad that they seem to 
be the main index to ask. At least the folks at the Transparent Language Popularity 
Index seem to be still halfway sane.

■_

2011年04月07日

■_

今日(7日)の地震でみねこあさんの部屋がどうなったのか心配であります。

■_ Rの起動時メッセージ文字化け

一歩前進。locale の設定が必要だった。 ↓のプログラムをmingw のgccあたりでコンパイルして実行すると、 xpとそれより前のものは同じ内容が4行出力されますが、 Vista以降(といいつつサーバーOSはわかりませんが)だと 二行目が半角カナになります。

#include <windows.h>
#include <stdio.h>
#include <locale.h>
int
main()
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    char *msgs[] = {
        /* " と      入      力      す      れ      ば" */
        "\x82\xC6\x93\xFC\x97\xCD\x82\xB7\x82\xEA\x82\xCE\n",
        "\x82",
        "\xc6",
        "\x93",
        "\xfc",
        "\x97",
        "\xcd",
        "\x82",
        "\xb7",
        "\x82",
        "\xea",
        "\x82",
        "\xce\n",
        NULL
    };
    char **p;

    setlocale(LC_ALL, ""); /*!!!*/
    for (p=msgs; *p; p++) {
        printf("%s", *p);
        fflush(stdout);
    }

    for (p=msgs; *p; p++) {
        DWORD lpwritecount = 0;
        WriteConsole(hStdout, *p, (DWORD)strlen(*p), &lpwritecount, NULL);
    }
    return 0;
}

Vista、7 だとこう

と入力すれば
ニヘキホ
と入力すれば
と入力すれば

xp だとこう

と入力すれば
と入力すれば
と入力すれば
と入力すれば

で、ソースコードのこの辺の問題だとは思うんだけど、 どうすればいいのやら。

src/gnuwin32/rui.c

int setupui(void)
{
    char *p, *ctype, Rlocale[1000] = ""; /* Windows' locales can be very long */

    initapp(0, 0);

    /* set locale before doing anything with menus */
    setlocale(LC_CTYPE, ""); /* necessary in case next fails to set
				a valid locale */
    if((p = getenv("LC_ALL"))) strcpy(Rlocale, p);
    if((p = getenv("LC_CTYPE"))) strcpy(Rlocale, p);
    if (strcmp(Rlocale, "C") == 0) strcpy(Rlocale, "en");
    setlocale(LC_CTYPE, Rlocale);
    mbcslocale = MB_CUR_MAX > 1;
    ctype = setlocale(LC_CTYPE, NULL);
    p = strrchr(ctype, '.');
    if(p && isdigit(p[1])) localeCP = atoi(p+1); else localeCP = 1252;

一応、対応する環境変数をいろいろ設定してみたのだけど、 ja_JP.ShiftJIS とか japanese_Japan.932 とかでもだめだった (違うパターンの文字化けが発生)。

Windows 版 R は MinGW 使ってるのがわかったので、ビルド環境構築しないとなあ。

■_ Delayed April Fool

意図したものかどうかはわかりませんが、エイプリルフールネタの英文記事を 数日遅れで翻訳を公開というのもなんというかその

【関数】Erlang Part 2【エリクソン】 

93 デフォルトの名無しさん [sage] 2011/04/07(木) 09:11:31.10 ID: Be:
    http://www.infoq.com/jp/news/2011/04/erlang-copied-jvm-and-scala

    Erlang を共同で開発した Joe Armstrong と Robert Virding 両氏が,Erlang が Java から多大な着想を得たことを認めている。

    ErlangFactory 2011 SF で行われたインタビューで両氏は,Erlang では「プロセス」と呼んでいるものを作る上で,
    Scala の Actor が大きな影響を与えているという,以前からあった噂をついに
    肯定したのだ。さらに Erlang の VM が,かの有名な Java 仮想マシン (Java Virtual
    Machine,JVM) のクローン同然のものであることも告白した。 

94 デフォルトの名無しさん [sage] 2011/04/07(木) 09:18:19.82 ID: Be:
    >>93
    うわ、これはショックだ
    そうじゃないかと思ってはいたけど両御大の言葉ともなると
    つらいものがあるな…漏れはArmstrong本で勉強したわけだし
    きっと何か事情があるんだと思うな…そうであってほしい 

95 デフォルトの名無しさん [sage] 2011/04/07(木) 09:30:56.90 ID: Be:
    >>94
    >かの有名な JVM に回帰すること,の2点を約束している。
    むしろこのあたりでちょっとうれしかったり

96 デフォルトの名無しさん [sage] 2011/04/07(木) 09:31:33.38 ID: Be:
    >>94
    Posted by Sadek Drobi on Apr 01, 2011

97 デフォルトの名無しさん [sage] 2011/04/07(木) 09:33:02.12 ID: Be:
    >>96
    ぐはぁ、そういう記事を1週間も遅れて貼るかなもう

98 デフォルトの名無しさん [sage] 2011/04/07(木) 09:55:37.68 ID: Be:
    >>97
    しかも>>94は縦読みだ。 

99 デフォルトの名無しさん [sage] 2011/04/07(木) 14:57:04.63 ID: Be:
    April Fool 

100 デフォルトの名無しさん [sage] 2011/04/07(木) 16:20:29.39 ID: Be:
    >>99
    that's right! 

101 デフォルトの名無しさん [sage] 2011/04/07(木) 20:25:44.71 ID: Be:
    >>94
    Cool ! 
プログラミング言語 Scala 5冊目 

471 デフォルトの名無しさん [sage] 2011/04/07(木) 09:12:30.95 ID: Be:
    http://www.infoq.com/jp/news/2011/04/erlang-copied-jvm-and-scala

    Erlang を共同で開発した Joe Armstrong と Robert Virding 両氏が,Erlang が Java から多大な着想を得たことを認めている。

    ErlangFactory 2011 SF で行われたインタビューで両氏は,Erlang では「プロセス」と呼んでいるものを作る上で,
    Scala の Actor が大きな影響を与えているという,以前からあった噂をついに
    肯定したのだ。さらに Erlang の VM が,かの有名な Java 仮想マシン (Java Virtual
    Machine,JVM) のクローン同然のものであることも告白した。 

472 デフォルトの名無しさん [sage] 2011/04/07(木) 09:29:15.28 ID: Be:
    >>471
    元記事のURLを載せないとフェアじゃない。

    http://www.infoq.com/news/2011/04/erlang-copied-jvm-and-scala

    Erlang Copied Scala's Actors & Erlang's VM is almost a Clone of the JVM
    Posted by Sadek Drobi on Apr 01, 2011 

473 デフォルトの名無しさん [sage] 2011/04/07(木) 10:08:11.74 ID: Be:
    ErlangってJavaより古いんだ 

474 デフォルトの名無しさん [sage] 2011/04/07(木) 11:09:11.27 ID: Be:
    翻訳で4/6に延期されるとか、新しいのか? 

475 デフォルトの名無しさん [sage] 2011/04/07(木) 11:17:58.85 ID: Be:
    1986年に社内公開で、一般公開は1998だと?
    javaの一般公開が1995で、開発開始が1990
    JVMの件は、直接関係ないんじゃないかな 

■_ R

Windows でビルドにするときの情報がこの辺に

R Installation and Administration
Appendix D The Windows toolset

If you want to build R or add-on packages from source in Windows, you will need to 
collect, install and test an extensive set of tools. See 
http://www.murdoch-sutherland.com/Rtools/ for the current locations and other updates 
to these instructions. (Most Windows users will not need to build add-on packages from 
source; see Add-on packages for details.)

We have found that the build process for R is quite sensitive to the choice of tools: 
please follow our instructions exactly, even to the choice of particular versions of 
the tools.35 The build process for add-on packages is somewhat more forgiving, but we 
recommend using the exact toolset at first, and only substituting other tools once you 
are familiar with the process.

略
You will need the following items to build R and packages. See the subsections below 
for detailed descriptions.

   * The command line tools (in Rtools*.exe)
   * The MinGW toolchain to compile C, Fortran and C++.

For installing simple source packages containing data or R source but no compiled code, 
none of these are needed. Perl is no longer needed to build R nor to install nor 
develop source packages.


Our toolset contains copies of Cygwin DLLs that may conflict with other ones on your 
system if both are in the path at once. The normal recommendation is to delete the 
older ones; however, at one time we found our tools did not work with a newer version 
of the Cygwin DLLs, so it may be safest not to have any other version of the Cygwin 
DLLs in your path.

あまり苦労しないでビルド環境作れそう?

■_ もなど

YHCの話は数日前から流れてましたが、

York Haskell Compiler: Yhc is dead
Yhc is dead

Someone recently asked on the Yhc mailing list if Yhc was dead. The answer is yes, 
noone has been working on the compiler for several years. The nhc98 compiler, from 
which Yhc originally forked, is still maintained. Since this is the end of Yhc, I 
thought I'd share a few random thoughts about Yhc:

   * Writing a Haskell compiler is a big undertaking, and the work required to compile 
     a moderate number of programs from Hackage is immense. Too many libraries rely on 
     something GHC specific - either language or runtime features. The GHC team have gone 
     out of their way to ensure that their compiler is by default a standard Haskell 
     compiler, which has kept Haskell as a viable language separate from GHC. But without 
     widely-used competing implementations, programs tend to end up depending on GHC.

略
   * If you don't understand monads, you aren't yet ready to write a Haskell compiler.

   * If you have a group of Haskell programmers in the same place, you should try a 
     group project. It's fun.

   * The biggest challenge for Yhc was the build system - we ended up with 10,000 lines
     of Python Scons scripts. Without a robust build system nothing else matters. 
     When our sole Python hacker left the team that was the beginning of the end.



Working on Yhc was fun, and I learned a lot. Thanks to everyone who was involved.

「モナドを理解していないのなら、まだHaskellコンパイラーを書ける段階ではない」と。

■_

2011年04月06日

■_

なんか(風邪やら何やらで)喉がおかしいって人が多いですね。

R のソースツリー眺めてると結構面白い。 結構いろんなものを取り込んでるのね。

■_

■_ まにふぇすと

The Destructive Programming Manifesto : programming 経由で。

The Destructive Programming Manifesto

The Destructive Programming Manifesto
(破壊的プログラミング声明)

We are programmers. We strive to write good code.
われわれはプログラマーである。
われわれは優れたコードを書くために奮闘する。

We acknowledge that efficient code is often locally unclear.
われわれは効率的なコードがしばしば局所的には不明瞭であることを認める。

We cannot stand writing more comments than code to document our hacks.
われわれはわれわれのハックを説明するためにコードを書くよりもドキュメントを書くことを良しとしない。

We would rather not have to fix code we wrote ages ago.
われわれはかつて書いたコードを修正する必要を認めない

We are sick of trying to decipher code others wrote.
われわれは他者の書いたコードを解読することにうんざりしている。

Hence, this is how we work:
したがって、われわれの仕事のありようとは以下の通りである。

We write code as small self-contained blocks with well-defined interfaces.

われわれはきちんと定義されたインターフェースを持ち小さく完結したブロックとしてコードを書く。

Sometimes, we use software techniques to enforce them.
われわれはそれを強制するためにソフトウェアテクニックを駆使することもある。

When a block is inefficient or behaves incorrectly, we do not read its code.
あるブロックが非効率的であったり不適切な振る舞いをするものであれば、われわれはそのコードを読まない。

We re-implement it. Because it's faster. And because it gives us fewer headaches.
われわれはそのようなコードを再実装する。
なぜならばそうすることがより早く、また、頭痛の種が少なくなるからである。

いまいちそれっぽい文章にならんなw

■_ もしも

VisiCalc (というかスプレッドシート) に特許が成立していたら。 VisiCalc - Wikipedia

What If VisiCalc Had Been Patented? | Techdirt
What If VisiCalc Had Been Patented?

Dan Bricklin, the creator of the first spreadsheet program, VisiCalc, has been 
mentioned in a number of articles recently concerning the issue of software patents, 
and he's now speaking up about the basic question of what would have happened if he'd 
been able to patent VisiCalc. (略)

■_ 文字化け

Windows版のRの話。 Vista 以降のコマンドプロンプトで rterm.exe (r.exe 経由でも同じ)を起動すると 次のように文字化けが。

>rterm

R version 2.11.0 (2010-04-22)
Copyright (C) 2010 The R Foundation for Statistical Computing
ISBN 3-900051-07-0

RヘAゥRネ\tgEFAナAuョSノウロリvナキB
フノ]ヲホAゥRノアトzzキアニェナォワキB
zzフレラノヨオトヘA'license()'「ヘ'licence()'ニヘオトュセウ「B

Rヘスュフv」メノ、ッvWFNgナキB
レオュヘ'contributors()'ニヘオトュセウ「B
ワスARRフpbP[Woナィナpキロフ`ョノツ「トヘ
'citation()'ニヘオトュセウ「B

'demo()'ニヘキホfンアニェナォワキB
'help()'ニキホICwvェoワキB
'help.start()'ナHTMLuEUノwvェンワキB
'q()'ニヘキホRIケオワキB

> q()
 作業スペースを保存しますか?  [y/n/c]: n ←このメッセージは化けない

xp までだときちんと出る。

R version 2.11.0 (2010-04-22)
Copyright (C) 2010 The R Foundation for Statistical Computing
ISBN 3-900051-07-0

Rは、自由なソフトウェアであり、「完全に無保証」です。 
一定の条件に従えば、自由にこれを再配布することができます。 
配布条件の詳細に関しては、'license()'あるいは'licence()'と入力してください。 

Rは多くの貢献者による共同プロジェクトです。 
詳しくは'contributors()'と入力してください。 
また、RやRのパッケージを出版物で引用する際の形式については
'citation()'と入力してください。 

'demo()'と入力すればデモをみることができます。 
'help()'とすればオンラインヘルプが出ます。 
'help.start()'でHTMLブラウザによるヘルプがみられます。 
'q()'と入力すればRを終了します。 

という話題は以前にも書いたのですが、化けたメッセージを調べてみると、 どうもShiftJISで出力したメッセージ文字列をバイト列として見たときに 半角カナやアルファベットと同じパターンのバイトだけ出てきているようです。 この手の現象(やそれを引き起こす仕様変更)を、どこかで聞いた覚えがあるんですが どこだったかなあ。

Win32API の WriteConsole で 1バイトずつ出力したら同様の文字化けが起きるかと思って試しても きちんと出力されてしまった。

■_ 日経ソフトウエア2002年7月号

このインタビュー記事は知らなかった。 どっかで読めないかなあ(とはいえ国会図書館までいくのは)。

ボーランド - Wikipedia
1995年、ソフトウェア開発ツールで巻き返しを図るボーランドは、Windows時代に対応したRADツ
ール Delphiを発売。アンダース・ヘルスバーグ(Anders Hejlsberg)による精練された設計は、
マイクロソフト製ツールを圧倒した。これに対してマイクロソフトは、開発部門のトップであっ
たポール・グロス(Paul Gross)上級副社長を筆頭に、アンダース・ヘルスバーグなど主要なボ
ーランドの技術者を30ヶ月間に34人引き抜き対抗。「Dead Borlanders Society」と皮肉られる
有様だった[1]。怒ったボーランドはマイクロソフトを訴え、長期にわたる法廷闘争が繰り広げ
られた。

なお、この引き抜き劇の真相について、アンダース・ヘルスバーグ氏は日経ソフトウェア2002年
7月号のインタビューで、直接的な原因は1994年にフィリップ・カーン氏が追放されたのを皮切
りに、ボーランド社が開発ツール部門の廃止および大量リストラを計画したことが発端であり、
リストラ対象となった開発者たちの生活を守るため、賛同者を引き連れてマイクロソフトに移籍
したものであると語っている。

2011年04月05日

■_

DDDの日本語訳、先行販売が始まったそうで (池袋のジュンク堂と秋葉原の書泉ブックタワーに入ったというツイートは見た)。

■_ 英語難しい

新山さんの訳を読んでいて気になったんですが

エドガー・W・ダイクストラ: 謙虚なるプログラマ (The Humble Programmer)

最初の自動計算機というものはどれもみなユニークで、一台しかなく、 どれもみなわくわくす
る実験室のような環境に置かれていました。

謙虚なるプログラマ - taro-nishino の日記

最初の自動電子計算機はすべてユニークで、単一のマシンのコピーだった。それらはすべて、実
験的研究所の刺激的な趣きの環境の中にあった。

原文はどうなのかなあとあたってみると

E.W.Dijkstra Archive: The Humble Programmer (EWD 340)

The first automatic electronic computers were all unique, single-copy machines and 
they were all to be found in an environment with the exciting flavour of an 
experimental laboratory.

全体の流れを考えれば確かに一台こっきりというのがわかるけど、 single-copy という語だけ見てはそう判断できないような気がする(^^; 参考までに、ACMチューリング賞講演録にあった訳はこう(訳者は木村泉さん)。


初期の電子計算機は、いずれも1台かぎりのもので、実験研究室特有の胸を躍らせるような雰囲
気のもとにおかれていました。

  

せっかく引っ張り出したのでついでに。

エドガー・W・ダイクストラ: 謙虚なるプログラマ (The Humble Programmer)

そして、60年代中期に、おそろしいことが起きてしまったのです。 いわゆる第3世代コンピュー
タと呼ばれるものの登場です。 公式な文献によれば、これらの設計上の目標はおもに 価格/性
能比であったとされています。もし“性能”というものを そのマシンの各構成部分の駆動サイ
クルだと定義すれば、おそらくその目標性能の大部分は、 必要かどうかも疑わしい内部処理に
よって達成される設計になってしまうでしょう。 また、“価格”というものをハードウェアの
値段だと定義すれば、 おそらくそれは非常にプログラムしにくい設計になってしまうに 違いあ
りません。たとえば、その命令コードはプログラマまたは システムのどちらかに対して、早い
うちからがんじがらめの決定を 強制するものになるかもしれず、それが生みだす対立はとうて
い 解消できなくなってしまうかもしれません(*2)。 そして、これらの不愉快な可能性は、おお
むね現実のものとなってしまったようでした。

(*2: この部分の訳は自信がない。 "the order code might be such as to enforce, either upon the
progrmmer or upon the system, early binding decisions presenting conflicts that really cannot
be resolved.") 

この部分を講演録から。

 さて 1960年代の中頃に一つのおそろしい出来事が起こりました。いわゆる第3世代の計算機が
世にあらわれたのです。公式の文献によりますと、それらの計算機の設計目標は価格対性能比を
下げることであるとされています。しかし、もし「性能」を計算機の種々の構成部品の繰り返し
動作周波数を指すものと解すれば、内部で大した意味もない制御動作を繰り返すことによって設
計目標を達成する、というようなばかな話に対して歯止めがないことになります。また、価格を、
ハードウェアに対して支払われる価格と解すれば、プログラムが途方もなく作りにくいような設
計に到達してしまうことに対しても歯止めがありません。たとえばプログラマまたはシステムに
対して、あとで解決不能の矛盾を生じさせる拘束的な決定を早いうちに下さざるを得なくさせる
ような命令体系が作られる、ということが考えられます。そしてこれらのおそれは、かなりの程
度にわたって現実となったように思われます。

  

■_

■_ Mirah

JVM 上で動く言語ってのもどんどん出ますねえ。

Main

The Mirah Programming Language

Mirah is a new way of looking at JVM languages. In attempting to build a replacement 
for Java, we have followed a few guiding principals:

    * No runtime library (ランタイムライブラリ不要)

Mirah does not impose any jar files upon you. YOU decide what your application's 
dependencies should be.

Mirah は「あなた」に依存する jar ファイルを一切仮定しません。
「あなた」はアプリケーションが依存すべきものだけを決めれば良いのです。

    * Clean, simple syntax (きれいで単純な構文)

We have borrowed heavily from Ruby, but added static typing and minor syntax changes 
to support the JVM's type system. The result is pleasing to the eye, but as powerful 
as Java.

構文の多くを Ruby から拝借しましたが、静的な型付けを追加し、
JVMの型システムをサポートするために小規模な構文の変更を行っています。
その結果として、目に優しくかつ、Javaと同程度に強力なものとなりました。

    * Metaprogramming and macros (メタプログラミングとマクロ)

Mirah supports various mechanisms for compile-time metaprogramming and macros. Much of 
the “open class” feel of dynamic languages is possible in Mirah.

Mirah はさまざまなコンパイル時メタプログラミングやマクロをサポートしています。
Mirah では、“オープンクラス”のような動的言語を思わせるものの大半が可能です。


    * No performance penalty (パフォーマンス上のペナルティなし)

Because Mirah directly targets the JVM's type system and JVM bytecode, it performs 
exactly as well as Java.

Mirah はJVMの型システムとJVM バイトコードを直接のターゲットとしているので、
その性能はJavaと遜色ないものです。

More about => MirahFeatures
以下略

2011年04月04日

■_

もー喉が。

■_

Python C モジュールコードリーディング

Python C API による拡張を学ぶ

C実装のプラクティス
 読みやすい/分かりやすい→テストしやすい
 設計
   データ構造
   エラー処理  Cでどう書く?

ドキュメント  Pythonインタプリタの拡張と埋め込み

Pythonの拡張方針 by Guido
  1.ピュアPythonライブラリ
  2. Cモジュールライブラリ
  3. 言語コアに組み込み
    (言語設計者たち~から)

Python実装とCの実装を持つモジュール
bisect
datetime
pickle
heapq
string
sringIO
などなど

今回はbisectを取り上げます
lib/bisect.py にピュアPython実装

Modules/_bisectmodule.c
/* Bisection algorithms. Drop in replacement for bisect.py

Converted to C by Dmitry Vasiliev (dima at hlabs.spb.ru).
*/

bisect_left と bisect_right があるのはなんで?
  →連続値に対する対応とか?

static PyObject *
bisect_right(PyObject *self, PyObject *args, PyObject *kw)
{
    PyObject *list, *item;
    Py_ssize_t lo = 0;
    Py_ssize_t hi = -1;
    Py_ssize_t index;
    static char *keywords[] = {"a", "x", "lo", "hi", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right",//←引数解析
        keywords, &list, &item, &lo, &hi))
        return NULL;
    index = internal_bisect_right(list, item, lo, hi);
    if (index < 0)
        return NULL;//←NULL を返すと処理系がよろしくやってくれる。たぶん。
    return PyLong_FromSsize_t(index);
}

呼び出し元が位置引数を使っているかキーワード引数を使っているか
getargs.c

/* Support for keyword arguments donated by
   Geoff Philbrick <philbric@delphi.hks.com> */

/* Return false (0) for error, else true. */
int
PyArg_ParseTupleAndKeywords(PyObject *args,
                            PyObject *keywords,
                            const char *format,
                            char **kwlist, ...)
{
    int retval;
    va_list va;

    if ((args == NULL || !PyTuple_Check(args)) ||
        (keywords != NULL && !PyDict_Check(keywords)) ||
        format == NULL ||
        kwlist == NULL)
    {
        PyErr_BadInternalCall();
        return 0;
    }

    va_start(va, kwlist);
    retval = vgetargskeywords(args, keywords, format, kwlist, &va, 0);
    va_end(va);
    return retval;
}

#define IS_END_OF_FORMAT(c) (c == '\0' || c == ';' || c == ':')

static int
vgetargskeywords(PyObject *args, PyObject *keywords, const char *format,
                 char **kwlist, va_list *p_va, int flags)
{
    char msgbuf[512];
    int levels[32];
    const char *fname, *msg, *custom_msg, *keyword;
    int min = INT_MAX;
    int i, len, nargs, nkeywords;
    PyObject *freelist = NULL, *current_arg;

    assert(args != NULL && PyTuple_Check(args));
    assert(keywords == NULL || PyDict_Check(keywords));
    assert(format != NULL);
    assert(kwlist != NULL);
    assert(p_va != NULL);

    /* grab the function name or custom error msg first (mutually exclusive) */
    fname = strchr(format, ':');
    if (fname) {
        fname++;
        custom_msg = NULL;
    }
    else {
        custom_msg = strchr(format,';');
        if (custom_msg)
            custom_msg++;
    }

    /* scan kwlist and get greatest possible nbr of args */
    for (len=0; kwlist[len]; len++)
        continue;
(略)


static Py_ssize_t
internal_bisect_right(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t hi)
{
    PyObject *litem;
    Py_ssize_t mid, res;

    if (lo < 0) {
        PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
        return -1;
    }
    if (hi == -1) {
        hi = PySequence_Size(list);//←abstract.c に実体がある
        if (hi < 0)
            return -1;
    }
    while (lo < hi) {
        mid = (lo + hi) / 2;
        litem = PySequence_GetItem(list, mid);//←abstract.c 内部の実装について。

↓ シーケンスであることが確定してるんじゃないの?
/*
PyObject *
PySequence_GetItem(PyObject *s, Py_ssize_t i)
{
    PySequenceMethods *m;

    if (s == NULL)
        return null_error();

    m = s->ob_type->tp_as_sequence;
    if (m && m->sq_item) {
        if (i < 0) {
            if (m->sq_length) {
                Py_ssize_t l = (*m->sq_length)(s); ←いちいち手繰っていっているので無駄に見える
                if (l < 0)
                    return NULL;
                i += l;
            }
        }
        return m->sq_item(s, i);
    }

    return type_error("'%.200s' object does not support indexing", s);
}

*/
        if (litem == NULL)
            return -1;
        res = PyObject_RichCompareBool(item, litem, Py_LT);
        Py_DECREF(litem);//←なんで?
        if (res < 0)
            return -1;
        if (res)
            hi = mid;
        else
            lo = mid + 1;
    }
    return lo;
}

・リファレンスカウント方式難しい
・おそらくここで多少の「最適化」をしても労力に見合うだけの性能向上はないだろう
  →だから一見無駄に見えるようなこともしている


static struct PyModuleDef _bisectmodule = {
    PyModuleDef_HEAD_INIT,
    "_bisect",
    module_doc,
    -1,
    bisect_methods,
    NULL,
    NULL,
    NULL,
    NULL
};

→ レイアウトの詳細は moduleobject.h 参照

↓
typedef struct PyModuleDef{
  PyModuleDef_Base m_base;
  const char* m_name;
  const char* m_doc;
  Py_ssize_t m_size;
  PyMethodDef *m_methods;
  inquiry m_reload;
  traverseproc m_traverse;
  inquiry m_clear;
  freefunc m_free;
}PyModuleDef;

・リファレンスカウントのinc/decはノウハウ?
     書くときは気にしないといけない
     読むときは気にする必要はない
 Perl の拡張はマクロ名が短いので分かりづらい
 Python は長くて分かりやすい
 C++ の人は Boost使うといいよ!
 サイソン(cython?)
 
アルゴリズムの実習としてPythonのソースを使ってみたい

C APIを使う

次 → 一ヶ月から二ヶ月? 未定
次回のお題 dictobject とそのAPI

CPython 3.2 ソースコードリーディング 第 2 回 - [PARTAKE]

やっと終わった ○| ̄|_

■_

■_

関数型言語ML (SML, OCaml, etc.), Part 6 

388 デフォルトの名無しさん [sage] 2011/03/11(金) 19:43:34.45 ID: Be:
    おいおい、岡村!アラン、見ランダ?
    Yacc束してたのに、Matlab。

    あだー。アラン、隙間フェチ、すから。
    見つけるのは一苦労じゃろーね。Sque無い
    嗚呼、くっ。一緒にエイダみる予定だったのに・・
    遅coqしたら理彩のレイジがMaximaになる
    メーリングリストで蓮家等に聞いてミルか
    Amigaとう。んじゃ,またAgda!
    Orc、またAgdaな 

389 デフォルトの名無しさん [sage] 2011/03/11(金) 21:16:39.93 ID: Be:
    おつかれ~ 

■_

Mathematica home edition が…という人は結構いるのかなあ。 数学板にスレッドがあった。

〓 Mathematica 5 〓 

176 132人目の素数さん [sage] 2010/12/12(日) 01:26:39 ID: Be:
    Home Editionは具体的にどの機能が制限されているんですか? 

177 132人目の素数さん [sage] 2010/12/12(日) 03:21:48 ID: Be:
    >>176
    機能制限というか、日本ではHome Edition単体の販売はなく、
    プレミア版のおまけのうえ、日本版はプレミア期間タイマー
    が作動します。
    またVer.8宣伝の機能の中には、Wolfram|Alphaとの接続が
    必要のようですね。 

178 132人目の素数さん [sage] 2010/12/12(日) 09:02:15 ID: Be:
    >>177
    ありがとうございます
    でも、ごめんなさいよく分からないです・・・・
    とにかく日本で販売はしてないのですね 

179 132人目の素数さん [sage] 2010/12/13(月) 13:13:13 ID: Be:
    >>176
    機能制限はないはず。個人的使用制限があって、32ビット版らしいが。
    しかし日本での販売は無いってさ、今時ダウンロード販売なんて簡単な事なのにね。 

223 132人目の素数さん [sage] 2010/12/23(木) 09:53:45 ID: Be:
    423500円は今のレートで5 067.601ドル!!!
    アメリカじゃ3000ドル行かないだろ?そもそも295ドルのHome Edition売ってるし。
    ボッタクリだぜ! 

224 132人目の素数さん [] 2010/12/23(木) 10:00:25 ID: Be:
    不買運動で抗議しよう 

225 132人目の素数さん [sage] 2010/12/23(木) 10:22:15 ID: Be:
    不買運動って、、、そもそも買えるか! 

225 を読んでとても悲しくなった ○| ̄|_

2011年04月03日

■_

・先週半ばくらいから咳が断続的に出たり喉に違和感があったり(熱はない)で 日曜日はおとなしくしてた。が、こんなときでも積読を解消できなかったりする。うひ。

工学部ヒラノ教授 ガー・レイノルズ シンプルプレゼン
読んだのは、昨日ジュンク堂で買ったばかりのこれ。 大学の先生(教授)てのはたいへんなのねえ。

一部で話題になってますが Lexical bindingJust a note that the lexbind branch has been merged into trunk,と アナウンスされているように、Emacs Lisp のバインディングが (指定が必要とはいえ) lexical binding になったということらしく。 アナウンスされた日が4/1だったので、You couldn't wait just one more day? :-) (Re: Lexical binding) という反応が返ってきてたり。 コードでどこがどのくらい変わったのか確かめてみたいと思ったけど bazzaar とか入れないといかんのか… reddit 方面の反応 → Emacs Lisp now lexically scoped. "Oh, very funny". No, really. : programming

行きたい…が、広島かあ 企画展 「コンピュータの歴史展」 - 手回し計算機からパソコン、そしてスーパーコンピュータ - - 新着情報ブログ

■_ J9

この辺ではなく。
銀河旋風ブライガー音楽集 銀河烈風バクシンガー 音楽集 銀河疾風サスライガー音楽集

J言語 

118 デフォルトの名無しさん [sage] 2011/03/24(木) 17:49:42.99 ID: Be:
    J7オープンソース化
    ttp://www.jsoftware.com/source.htm

    これでARMでも動くようになったらうれしい。 

119 デフォルトの名無しさん [sage] 2011/03/24(木) 19:31:55.69 ID: Be:
    >>118
    祝!

    A+に続く2つめの快挙。
    正統性から言って、JsoftwareはMorgan Stanleyより上だ。 

120 デフォルトの名無しさん [sage] 2011/03/28(月) 20:28:14.76 ID: Be:
    >>118
    > これでARMでも動くようになったらうれしい。

    iPodやAndroid端末で使えるようになれば良いと言う意味ですよね?
    現状では遊べるアプリが少なすぎます。 

121 デフォルトの名無しさん [sage] 2011/04/01(金) 15:25:15.98 ID: Be:
    OpenCL対応J8アルファ版

    http://www.jsoftware.com/alpha.htm 

122 デフォルトの名無しさん [sage] 2011/04/02(土) 17:14:23.93 ID: Be:
    スルーされて哀しいw

    今気づいたけど、スレが立ってもう1年以上経過してるんだな。 

123 デフォルトの名無しさん [sage] 2011/04/02(土) 22:33:54.45 ID: Be:
    J9って知ってるかい? 

124 デフォルトの名無しさん [sage] 2011/04/03(日) 06:48:09.52 ID: Be:
    情け無用でさらに複雑化するんだな! 

J9 といえば大昔のビデオデッキでそんな名前のやつがあったような。

■_ CPython ソースコードリーディング

つづき。


PyObject
PyVarObject

/* PyObject_HEAD defines the initial segment of every PyObject. */
#define PyObject_HEAD                   PyObject ob_base;

#define PyObject_HEAD_INIT(type)        \
    { _PyObject_EXTRA_INIT              \
    1, type },

#define PyVarObject_HEAD_INIT(type, size)       \
    { PyObject_HEAD_INIT(type) size },

ob_refcount
ob_size

bytesobject

/*
Type PyBytesObject represents a character string.  An extra zero byte is
reserved at the end to ensure it is zero-terminated, but a size is
present so strings with null bytes in them can be represented.  This
is an immutable object type.  ← ゼロ終端を保証するために余計な1バイトがあるという記述

There are functions to create new string objects, to test
an object for string-ness, and to get the
string value.  The latter function returns a null pointer
if the object is not of the proper type.
There is a variant that takes an explicit size as well as a
variant that assumes a zero-terminated string.  Note that none of the
functions should be applied to nil objects.
*/

/* Caching the hash (ob_shash) saves recalculation of a string's hash value.
   This significantly speeds up dict lookups. */

#ifndef Py_LIMITED_API
typedef struct {
    PyObject_VAR_HEAD
    Py_hash_t ob_shash;
    char ob_sval[1];  //←

    /* Invariants:
     *     ob_sval contains space for 'ob_size+1' elements.
     *     ob_sval[ob_size] == 0.
     *     ob_shash is the hash of the string or -1 if not computed yet.
     */
} PyBytesObject;
#endif

object の型の定義、宣言 Include/
  実装 Objects/

byteobject immutable なバイト列

static PyBytesObject *characters[UCHAR_MAX + 1];
static PyBytesObject *nullstring;

/* PyBytesObject_SIZE gives the basic size of a string; any memory allocation
   for a string of length n should request PyBytesObject_SIZE + n bytes.

   Using PyBytesObject_SIZE instead of sizeof(PyBytesObject) saves
   3 bytes per string allocation on a typical system.//←32bit環境?>3bytes
*/
#define PyBytesObject_SIZE (offsetof(PyBytesObject, ob_sval) + 1)//アライメントの大きさに応じて切り上げたもの?

/*
   For both PyBytes_FromString() and PyBytes_FromStringAndSize(), the
   parameter `size' denotes number of characters to allocate, not counting any
   null terminating character.

   For PyBytes_FromString(), the parameter `str' points to a null-terminated
   string containing exactly `size' bytes.

   For PyBytes_FromStringAndSize(), the parameter the parameter `str' is
   either NULL or else points to a string containing at least `size' bytes.
   For PyBytes_FromStringAndSize(), the string in the `str' parameter does
   not have to be null-terminated.  (Therefore it is safe to construct a
   substring by calling `PyBytes_FromStringAndSize(origstring, substrlen)'.)
   If `str' is NULL then PyBytes_FromStringAndSize() will allocate `size+1'
   bytes (setting the last byte to the null terminating character) and you can
   fill in the data yourself.  If `str' is non-NULL then the resulting
   PyBytes object must be treated as immutable and you must not fill in nor
   alter the data yourself, since the strings may be shared.

   The PyObject member `op->ob_size', which denotes the number of "extra
   items" in a variable-size object, will contain the number of bytes
   allocated for string data, not counting the null terminating character.  It
   is therefore equal to the equal to the `size' parameter (for
   PyBytes_FromStringAndSize()) or the length of the string in the `str'
   parameter (for PyBytes_FromString()).
*/
PyObject *
PyBytes_FromStringAndSize(const char *str, Py_ssize_t size)
{
    register PyBytesObject *op;
    if (size < 0) {
        PyErr_SetString(PyExc_SystemError,
            "Negative size passed to PyBytes_FromStringAndSize");
        return NULL;
    }
    if (size == 0 && (op = nullstring) != NULL) {
#ifdef COUNT_ALLOCS
        null_strings++;
#endif
        Py_INCREF(op);
        return (PyObject *)op;
    }
    if (size == 1 && str != NULL &&
        (op = characters[*str & UCHAR_MAX]) != NULL) ←長さ1の文字列(1byte文字のみ)
    {
#ifdef COUNT_ALLOCS
        one_strings++;
#endif
        Py_INCREF(op);
        return (PyObject *)op;
    }

    if (size > PY_SSIZE_T_MAX - PyBytesObject_SIZE) {
        PyErr_SetString(PyExc_OverflowError,
                        "byte string is too large");
        return NULL;
    }

    /* Inline PyObject_NewVar */
    op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size);//←NUL文字分が加算されている
    if (op == NULL)
        return PyErr_NoMemory();
    PyObject_INIT_VAR(op, &PyBytes_Type, size);
    op->ob_shash = -1;
    if (str != NULL)
        Py_MEMCPY(op->ob_sval, str, size);
    op->ob_sval[size] = '\0';
    /* share short strings */
    if (size == 0) {
        nullstring = op;
        Py_INCREF(op);//呼び出し元でリファレンスカウントが減らされてもOK
    } else if (size == 1 && str != NULL) {
        characters[*str & UCHAR_MAX] = op;
        Py_INCREF(op);
    }
    return (PyObject *) op;
}

tupleオブジェクト
/*
Another generally useful object type is a tuple of object pointers.
For Python, this is an immutable type.  C code can change the tuple items
(but not their number), and even use tuples are general-purpose arrays of
object references, but in general only brand new tuples should be mutated,
not ones that might already have been exposed to Python code.

*** WARNING *** PyTuple_SetItem does not increment the new item's reference
count, but does decrement the reference count of the item it replaces,
if not nil.  It does *decrement* the reference count if it is *not*
inserted in the tuple.  Similarly, PyTuple_GetItem does not increment the
returned item's reference count.
*/

#ifndef Py_LIMITED_API
typedef struct {
    PyObject_VAR_HEAD
    PyObject *ob_item[1];←「ポインターの配列」

    /* ob_item contains space for 'ob_size' elements.
     * Items must normally not be NULL, except during construction when
     * the tuple is not yet visible outside the function that builds it.
     */
} PyTupleObject;
#endif

tuple のハッシュのキャッシュはできない

gcmodlue.c

リストオブジェクト
メモリブロックを別に確保して実体 (reallocateが必要なものはオブジェクトの中に持てない

/* List object interface */

/*
Another generally useful object type is an list of object pointers.
This is a mutable type: the list items can be changed, and items can be
added or removed.  Out-of-range indices or non-list objects are ignored.

*** WARNING *** PyList_SetItem does not increment the new item's reference
count, but does decrement the reference count of the item it replaces,
if not nil.  It does *decrement* the reference count if it is *not*
inserted in the list.  Similarly, PyList_GetItem does not increment the
returned item's reference count.
*/

typedef struct {
    PyObject_VAR_HEAD
    /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
    PyObject **ob_item; //←別割り当て(タプルはimmutableだがリストはmutable)

    /* ob_item contains space for 'allocated' elements.  The number
     * currently in use is ob_size.
     * Invariants:
     *     0 <= ob_size <= allocated
     *     len(list) == ob_size
     *     ob_item == NULL implies ob_size == allocated == 0
     * list.sort() temporarily sets allocated to -1 to detect mutations.
     *
     * Items must normally not be NULL, except during construction when
     * the list is not yet visible outside the function that builds it.
     */
    Py_ssize_t allocated;
} PyListObject;

dictobject
ハッシュ値
キー
値

最小のテーブルサイズ 8

#define PyDict_MINSIZE 8

typedef struct {
    /* Cached hash code of me_key. */
    Py_hash_t me_hash;
    PyObject *me_key;
    PyObject *me_value;
} PyDictEntry;

/*
To ensure the lookup algorithm terminates, there must be at least one Unused
slot (NULL key) in the table.
The value ma_fill is the number of non-NULL keys (sum of Active and Dummy);
ma_used is the number of non-NULL, non-dummy keys (== the number of non-NULL
values == the number of Active items).
To avoid slowing down lookups on a near-full table, we resize the table when
it's two-thirds full.
*/
typedef struct _dictobject PyDictObject;
struct _dictobject {
    PyObject_HEAD
    Py_ssize_t ma_fill;  /* # Active + # Dummy */
    Py_ssize_t ma_used;  /* # Active */

    /* The table contains ma_mask + 1 slots, and that's a power of 2.
     * We store the mask instead of the size because the mask is more
     * frequently needed.
     */
    Py_ssize_t ma_mask;

    /* ma_table points to ma_smalltable for small tables, else to
     * additional malloc'ed memory.  ma_table is never NULL!  This rule
     * saves repeated runtime null-tests in the workhorse getitem and
     * setitem calls.
     */
    PyDictEntry *ma_table;
    PyDictEntry *(*ma_lookup)(PyDictObject *mp, PyObject *key, Py_hash_t hash);
    PyDictEntry ma_smalltable[PyDict_MINSIZE];//内部に抱えているテーブル
};

Python では辞書はいろいろなところで使っている

テーブルサイズは2^n

ハッシュの詳細については以前書いたのと内容が被るので省略。

あと一回。

■_ Lisp Scheme Part31

さっきの Emacs の binding について。

Lisp Scheme Part31 

922 デフォルトの名無しさん [sage] 2011/04/03(日) 00:20:03.16 ID: Be:
    Emacs Lisp が色々とレキシカルスコープになるって話を聞いたんだけど、実際のところどうよ? 

923 デフォルトの名無しさん [sage] 2011/04/03(日) 00:40:04.61 ID: Be:
    >>922
    おお、とうとう lexbind が trunk に merge されたのね。

    http://comments.gmane.org/gmane.emacs.devel/138010

    これから Lisp 処理系を作る人は elisp 互換でも良いかも。 

924 デフォルトの名無しさん [sage] 2011/04/03(日) 08:59:54.54 ID: Be:
    ついにelispもレキシカルスコープかぁ

    これは歴史的だ 

925 デフォルトの名無しさん [sage] 2011/04/03(日) 09:20:45.49 ID: Be:
    >>923
    これマジなの?それともエイプリルフールネタ? 

926 デフォルトの名無しさん [sage] 2011/04/03(日) 09:54:03.91 ID: Be:
    うに板より転載
    >ここまで lexbind が trunk にマージされた話題無し
    >洒落た返信があったんで載せとく
    >
    >On 01/04/11 18:32, Stefan Monnier wrote:
    >> Just a note that the lexbind branch has been merged into trunk,
    >
    >wow, very cool... waaaiiit...
    >
    >;;; -*- lexical-binding: t -*-
    >(defun april-fools? ()
    >(let ((a t)
    >(check (let ((a nil)) (lambda () a))))
    >(funcall check)))
    >
    >(april-fools?) => nil
    >
    >This is great news.

927 デフォルトの名無しさん [sage] 2011/04/04(月) 00:58:32.40 ID: Be:
    dynamic binding だと check には (lambda nil a) が入って、
    lexical binding だと check には (lambda nil nil) が入るのか。
    なるほど・・・

924 が微妙にスルーされている気が。 あと let の動作がひっかかるんだけど気のせい?

■_

2011年04月02日

■_

hardly が handy に見えてたなんてだいぶ疲れているようだ(謎) Twitter / @murky-satyr: http://www.kt.rim.or.jp/%7 ... Twitter / @murky-satyr: 誤訳は未訳にしかず ...
まったくもって申し訳も ○| ̄|_

■_ CPython 3.2 ソースコードリーディング

メモ書きから。

ソースコードリーディング
於 森ビル19F

#cpython_reading
自己紹介


Cを使ったOOP実装
マルチプラットフォーム対応は大変→Javaっていいですね。
gtags

全体像
Py_Main
  ファイル指定がない場合はREPLが起動

run_mod → evalに相当

Modlues/python.c

stdin_is_interactive
RunMainFromImporter(filename);
PyRun_FileExFlags

メモリ管理
Arena 256kb Pool×64
Pool 4kb Block×n
Block 8-256bytes
*詳しくはGC本で! *
→ガベージコレクションのアルゴリズムと実装

ステートメント毎に分岐

PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
                  PyObject *locals, int closeit, PyCompilerFlags *flags)

ast_for_starred(struct compiling *c, const node *n)

        switch (TYPE(n)) {
            case expr_stmt:
                return ast_for_expr_stmt(c, n);
            case del_stmt:
                return ast_for_del_stmt(c, n);
            case pass_stmt:
                return Pass(LINENO(n), n->n_col_offset, c->c_arena);
            case flow_stmt:
                return ast_for_flow_stmt(c, n);
            case import_stmt:
                return ast_for_import_stmt(c, n);
            case global_stmt:
                return ast_for_global_stmt(c, n);
            case nonlocal_stmt:
                return ast_for_nonlocal_stmt(c, n);
            case assert_stmt:
                return ast_for_assert_stmt(c, n);
            default:
                PyErr_Format(PyExc_SystemError,
                             "unhandled small_stmt: TYPE=%d NCH=%d\n",
                             TYPE(n), NCH(n));
                return NULL;
        }

flow_stmt とはなにか?
↓これ。
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
(Grammar/Grammar)


PEP3107 アノテーションの処理はどうなっているか?

Grammar/Grammar
Include/graminit.h
tfpdef

自己紹介続き

 Ruby や C で書いたら Java で書き直された(メンテする人がいないので)

=====
CPython 3.2
evalを追う
一般的なインタープリターでのevalの実装
抽象構文木(AST) のノードに対して
現在の環境の下で
 より小さなノードがあれば評価
 それらを組み合わせて評価

ASTと値と環境の実装がわかればあとはわかる
ceval.c
co は code のこと

ASTと値と環境の実装を探ろう
AST
  PyCodeObjectという型がある
値
環境

PyCodeObject
AST Include/code.h
/* Bytecode object */
typedef struct {
    PyObject_HEAD
    int co_argcount;		/* #arguments, except *args */
    int co_kwonlyargcount;	/* #keyword only arguments */
    int co_nlocals;		/* #local variables */
    int co_stacksize;		/* #entries needed for evaluation stack */
    int co_flags;		/* CO_..., see below */
    PyObject *co_code;		/* instruction opcodes */
    PyObject *co_consts;	/* list (constants used) */
    PyObject *co_names;		/* list of strings (names used) */
    PyObject *co_varnames;	/* tuple of strings (local variable names) */
    PyObject *co_freevars;	/* tuple of strings (free variable names) */
    PyObject *co_cellvars;      /* tuple of strings (cell variable names) */
    /* The rest doesn't count for hash or comparisons */
    PyObject *co_filename;	/* unicode (where it was loaded from) */
    PyObject *co_name;		/* unicode (name, for reference) */
    int co_firstlineno;		/* first source line number */
    PyObject *co_lnotab;	/* string (encoding addr<->lineno mapping) See
				   Objects/lnotab_notes.txt for details. */
    void *co_zombieframe;     /* for optimization only (see frameobject.c) */
    PyObject *co_weakreflist;   /* to support weakrefs to code objects */
} PyCodeObject;

C でどのようにOOPを実現しているか? → 構造体を使って。
#COMとかもお仲間に入るのかしらん。

object.h
/*
Objects are structures allocated on the heap.  Special rules apply to
the use of objects to ensure they are properly garbage-collected.
Objects are never allocated statically or on the stack; they must be
accessed through special macros and functions only.  (Type objects are
exceptions to the first rule; the standard types are represented by
statically initialized type objects, although work on type/class unification
for Python 2.2 made it possible to have heap-allocated type objects too).

An object has a 'reference count' that is increased or decreased when a
pointer to the object is copied or deleted; when the reference count
reaches zero there are no references to the object left and it can be
removed from the heap.

(略)

Objects are always accessed through pointers of the type 'PyObject *'.
The type 'PyObject' is a structure that only contains the reference count
and the type pointer.  The actual memory allocated for an object
contains other data that can only be accessed after casting the pointer
to a pointer to a longer structure type.  This longer type must start
with the reference count and type fields; the macro PyObject_HEAD should be
used for this (to accommodate for future changes).  The implementation
of a particular object type can cast the object pointer to the proper
type and back.

A standard interface exists for objects that contain an array of items
whose size is determined when the object is allocated.
*/

opcode.h

まとめ
ASTといいつつ詳細を調べるとバイトコードっぽい


型オブジェクト
PyObject object.h
_typeobject.h object.h

#ifdef Py_LIMITED_API
typedef struct _typeobject PyTypeObject; /* opaque */
#else
typedef struct _typeobject {
    PyObject_VAR_HEAD
    const char *tp_name; /* For printing, in format "<module>.<name>" */
    Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

    /* Methods to implement standard operations */

    destructor tp_dealloc;
    printfunc tp_print;
    getattrfunc tp_getattr;
    setattrfunc tp_setattr;
    void *tp_reserved; /* formerly known as tp_compare */
    reprfunc tp_repr;

    /* Method suites for standard classes */

    PyNumberMethods *tp_as_number;
    PySequenceMethods *tp_as_sequence;
    PyMappingMethods *tp_as_mapping;

    /* More standard operations (here for binary compatibility) */

    hashfunc tp_hash;
    ternaryfunc tp_call;
    reprfunc tp_str;
    getattrofunc tp_getattro;
    setattrofunc tp_setattro;

    /* Functions to access object as input/output buffer */
    PyBufferProcs *tp_as_buffer;

    /* Flags to define presence of optional/expanded features */
    long tp_flags;

    const char *tp_doc; /* Documentation string */

    /* Assigned meaning in release 2.0 */
    /* call function for all accessible objects */
    traverseproc tp_traverse;

    /* delete references to contained objects */
    inquiry tp_clear;

    /* Assigned meaning in release 2.1 */
    /* rich comparisons */
    richcmpfunc tp_richcompare;

    /* weak reference enabler */
    Py_ssize_t tp_weaklistoffset;

    /* Iterators */
    getiterfunc tp_iter;
    iternextfunc tp_iternext;

    /* Attribute descriptor and subclassing stuff */
    struct PyMethodDef *tp_methods;
    struct PyMemberDef *tp_members;
    struct PyGetSetDef *tp_getset;
    struct _typeobject *tp_base;
    PyObject *tp_dict;
    descrgetfunc tp_descr_get;
    descrsetfunc tp_descr_set;
    Py_ssize_t tp_dictoffset;
    initproc tp_init;
    allocfunc tp_alloc;
    newfunc tp_new;
    freefunc tp_free; /* Low-level free-memory routine */
    inquiry tp_is_gc; /* For PyObject_IS_GC */
    PyObject *tp_bases;
    PyObject *tp_mro; /* method resolution order */
    PyObject *tp_cache;
    PyObject *tp_subclasses;
    PyObject *tp_weaklist;
    destructor tp_del;

    /* Type attribute cache version tag. Added in version 2.6 */
    unsigned int tp_version_tag;

#ifdef COUNT_ALLOCS
    /* these must be last and never explicitly initialized */
    Py_ssize_t tp_allocs;
    Py_ssize_t tp_frees;
    Py_ssize_t tp_maxalloc;
    struct _typeobject *tp_prev;
    struct _typeobject *tp_next;
#endif
} PyTypeObject;
#endif

PyLongObject(longobject.h)

2.x までは int (通常の整数) と long (多倍長の長整数)があったが 3.0 で long に統合された

_longobject.h

Include/longintrepr.h:89:struct _longobject {

struct _longobject {
}

longinterp.h
/* Long integer representation.
   The absolute value of a number is equal to
   	SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
   Negative numbers are represented with ob_size < 0;
   zero is represented by ob_size == 0.
   In a normalized number, ob_digit[abs(ob_size)-1] (the most significant
   digit) is never zero.  Also, in all cases, for all valid i,
   	0 <= ob_digit[i] <= MASK.
   The allocation function takes care of allocating extra memory
   so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available.

   CAUTION:  Generic code manipulating subtypes of PyVarObject has to
   aware that longs abuse  ob_size's sign bit.
*/

struct _longobject {
	PyObject_VAR_HEAD
	digit ob_digit[1]; ←実際にはこれは可変長配列になる
};

フレームって?

PyFrameOjbect frameobject.h

/* Frame object interface */

#ifndef Py_LIMITED_API
#ifndef Py_FRAMEOBJECT_H
#define Py_FRAMEOBJECT_H
#ifdef __cplusplus
extern "C" {
#endif

typedef struct {
    int b_type;			/* what kind of block this is */
    int b_handler;		/* where to jump to find handler */
    int b_level;		/* value stack level to pop to */
} PyTryBlock;

typedef struct _frame {
    PyObject_VAR_HEAD
    struct _frame *f_back;	/* previous frame, or NULL */
    PyCodeObject *f_code;	/* code segment */
    PyObject *f_builtins;	/* builtin symbol table (PyDictObject) */
    PyObject *f_globals;	/* global symbol table (PyDictObject) */
    PyObject *f_locals;		/* local symbol table (any mapping) */
    PyObject **f_valuestack;	/* points after the last local */
    /* Next free slot in f_valuestack.  Frame creation sets to f_valuestack.
       Frame evaluation usually NULLs it, but a frame that yields sets it
       to the current stack top. */
    PyObject **f_stacktop;
    PyObject *f_trace;		/* Trace function */

	/* In a generator, we need to be able to swap between the exception
	   state inside the generator and the exception state of the calling
	   frame (which shouldn't be impacted when the generator "yields"
	   from an except handler).
	   These three fields exist exactly for that, and are unused for
	   non-generator frames. See the SAVE_EXC_STATE and SWAP_EXC_STATE
	   macros in ceval.c for details of their use. */
    PyObject *f_exc_type, *f_exc_value, *f_exc_traceback;

    PyThreadState *f_tstate;
    int f_lasti;		/* Last instruction if called */
    /* Call PyFrame_GetLineNumber() instead of reading this field
       directly.  As of 2.3 f_lineno is only valid when tracing is
       active (i.e. when f_trace is set).  At other times we use
       PyCode_Addr2Line to calculate the line from the current
       bytecode index. */
    int f_lineno;		/* Current line number */
    int f_iblock;		/* index in f_blockstack */
    PyTryBlock f_blockstack[CO_MAXBLOCKS]; /* for try and loop blocks */
    PyObject *f_localsplus[1];	/* locals+stack, dynamically sized */
} PyFrameObject;

↑ 一つ前のフレーム、現在のコード、環境などが構造体としてまとまったもの。

frameobjet.c
コードや変数からフレームを作成
 おおよそ構造体にコピーしているだけ
フレームオブジェクトを作るときに
 ゾンビフレームというのが codee にあればそれを使う
なければフリーリストから取得
そこにもなければ malloc

/* Stack frames are allocated and deallocated at a considerable rate.
   In an attempt to improve the speed of function calls, we:

   1. Hold a single "zombie" frame on each code object. This retains
   the allocated and initialised frame object from an invocation of
   the code object. The zombie is reanimated the next time we need a
   frame object for that code object. Doing this saves the malloc/
   realloc required when using a free_list frame that isn't the
   correct size. It also saves some field initialisation.

   In zombie mode, no field of PyFrameObject holds a reference, but
   the following fields are still valid:

     * ob_type, ob_size, f_code, f_valuestack;

     * f_locals, f_trace,
       f_exc_type, f_exc_value, f_exc_traceback are NULL;

     * f_localsplus does not require re-allocation and
       the local variables in f_localsplus are NULL.

   2. We also maintain a separate free list of stack frames (just like
   floats are allocated in a special way -- see floatobject.c).  When
   a stack frame is on the free list, only the following members have
   a meaning:
    ob_type             == &Frametype
    f_back              next item on free list, or NULL
    f_stacksize         size of value stack
    ob_size             size of localsplus
   Note that the value and block stacks are preserved -- this can save
   another malloc() call or two (and two free() calls as well!).
   Also note that, unlike for integers, each frame object is a
   malloc'ed object in its own right -- it is only the actual calls to
   malloc() that we are trying to save here, not the administration.
   After all, while a typical program may make millions of calls, a
   call depth of more than 20 or 30 is probably already exceptional
   unless the program contains run-away recursion.  I hope.

   Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on
   free_list.  Else programs creating lots of cyclic trash involving
   frames could provoke free_list into growing without bound.
*/

static PyFrameObject *free_list = NULL;
static int numfree = 0;         /* number of frames currently in free_list */


PyEval_EvalCodeってどこから呼ばれるの?   → run_mod() から

ceval.c
PyObject *
PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
{
#ifdef DXPAIRS
    int lastopcode = 0;
#endif
    register PyObject **stack_pointer;  /* Next free slot in value stack */
    register unsigned char *next_instr;
    register int opcode;        /* Current opcode */
    register int oparg;         /* Current opcode argument, if any */
    register enum why_code why; /* Reason for block stack unwind */
    register int err;           /* Error status -- nonzero if error */
    register PyObject *x;       /* Result object -- NULL if error */
    register PyObject *v;       /* Temporary objects popped off stack */
    register PyObject *w;
    register PyObject *u;
    register PyObject *t;
    register PyObject **fastlocals, **freevars;
    PyObject *retval = NULL;            /* Return value */
    PyThreadState *tstate = PyThreadState_GET();
    PyCodeObject *co;

x だの v だのの一文字変数はナニモノ?
#何かのルールに従っての命名か

大量のマクロが定義されている
高速化のための努力
/* Computed GOTOs, or
       the-optimization-commonly-but-improperly-known-as-"threaded code"
   using gcc's labels-as-values extension
   (http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html).

   The traditional bytecode evaluation loop uses a "switch" statement, which
   decent compilers will optimize as a single indirect branch instruction
   combined with a lookup table of jump addresses. However, since the
   indirect jump instruction is shared by all opcodes, the CPU will have a
   hard time making the right prediction for where to jump next (actually,
   it will be always wrong except in the uncommon case of a sequence of
   several identical opcodes).

   "Threaded code" in contrast, uses an explicit jump table and an explicit
   indirect jump instruction at the end of each opcode. Since the jump
   instruction is at a different address for each opcode, the CPU will make a
   separate prediction for each of these instructions, which is equivalent to
   predicting the second opcode of each opcode pair. These predictions have
   a much better chance to turn out valid, especially in small bytecode loops.

(略)

   NOTE: care must be taken that the compiler doesn't try to "optimize" the
   indirect jumps by sharing them between all opcodes. Such optimizations
   can be disabled on gcc by using the -fno-gcse flag (or possibly
   -fno-crossjumping).
*/

実際のコード
        /* Main switch on opcode */
        READ_TIMESTAMP(inst0);

        switch (opcode) {

        /* BEWARE!
           It is essential that any operation that fails sets either
           x to NULL, err to nonzero, or why to anything but WHY_NOT,
           and that no operation that succeeds does this! */

        /* case STOP_CODE: this is an error! */

computed goto するために複雑になっている
  (→ ダイレクトスレッデッドコードとか調べよう)

NOP
LOAD_CONST
  stack machine ぽい?
 TARGET(BINARY_ADD を調べるとそれっぽい

スタックマシンなら、スタックトップを見て分岐する命令があるはず

        TARGET(BINARY_ADD)
            w = POP();
            v = TOP();
            if (PyUnicode_CheckExact(v) &&
                     PyUnicode_CheckExact(w)) {
                x = unicode_concatenate(v, w, f, next_instr);
                /* unicode_concatenate consumed the ref to v */
                goto skip_decref_vx;
            }

  あった


関数呼び出し CALL_FUNCTION
 call_function

        TARGET(CALL_FUNCTION)
        {
            PyObject **sp;
            PCALL(PCALL_ALL);
            sp = stack_pointer;
#ifdef WITH_TSC
            x = call_function(&sp, oparg, &intr0, &intr1);
#else
            x = call_function(&sp, oparg);
#endif
            stack_pointer = sp;
            PUSH(x);
            if (x != NULL)
                DISPATCH();
            break;
        }

関数呼び出しの本体

static PyObject *
call_function(PyObject ***pp_stack, int oparg
#ifdef WITH_TSC
                , uint64* pintr0, uint64* pintr1
#endif
                )
{
    int na = oparg & 0xff;
    int nk = (oparg>>8) & 0xff;
    int n = na + 2 * nk;
    PyObject **pfunc = (*pp_stack) - n - 1;
    PyObject *func = *pfunc;
    PyObject *x, *w;

    /* Always dispatch PyCFunction first, because these are
       presumed to be the most frequent callable object.
    */

optarg の下16ビットは引数の数を表している
na positional 引数
nk  キーワード引数 (キーワード、値のペアなので二倍)

    int na = oparg & 0xff;
    int nk = (oparg>>8) & 0xff;
    int n = na + 2 * nk;

---


disモジュールのdis()が便利

"""Disassembler of Python byte code into mnemonics."""

import sys
import types

from opcode import *
from opcode import __all__ as _opcodes_all

slideshare

=======
つづく。かもしれない。

■_

■_

久しぶりに池袋のジュンク堂に行った。

2011年04月01日

■_

それにつけても以下略

■_ 変数の頭につける$は

"Support variable names without dollar sign" : PHP

PHP :: Request #54325 :: Support variable names without dollar sign

Request #54325 	Support variable names without dollar sign
Submitted: 	2011-03-20 17:11 UTC 	Modified: 	2011-04-01 04:44 UTC 	
From: 				 	Assigned: 	
Status: 	Bogus 	Package: 	*General Issues
PHP Version: 	5.3.6 	OS: 	
Private report: 	No 	CVE-ID: 	
View Add Comment Developer Edit
 [2011-03-20 17:11 UTC] ahmetdevel at umich dot edu

Description:
------------
I believe the dollar sign in variable names to be a waste of precious keystrokes, 
and I would boldly suggest the requirement that variable names be prefixed with a 
dollar sign is removed. 

変数名についているドル記号は貴重なキーストロークの浪費であるとわたしは確信しています。
そこで変数名に前置されるドル記号を取り除く要求を強くここで求めるものであります。


Currently, undefined literals are interpreted as strings (with a "Notice" fired). 
This is a hardly useful feature, as most useful strings will contain spaces. A 
better use of such tokens would be to interpret them as variables.

現状では、未定義リテラルは文字列として解釈されます (with a "Notice" fired)。
これはとても便利な使いどころのない機能であり、大部分の有用な文字列がスペースを含むようになるでしょう含んでしまいます。
そのようなトークンのよりよい使用はそれを変数として解釈することです。

If this feature would not be seriously considered, I would appreciate any pointers 
into the relevant source code location(s) that needs to be modified to implement 
this feature.

もしこの機能が真剣に考慮されないのであれば、わたしは実装するのに必要となる
ソースコードの変更点すべてを提示するよういがあります。

Thanks,
AhmetSacan.


Patches

 
PHP Copyright © 2001-2011 The PHP Group

All rights reserved. 	Last updated: Sun Feb 27 03:01:04 2011 UTC

■_ スタックを使ってキューを実装

pozorvlak: Building a queue with two stacks

Building a queue with two stacks
二つのスタックを使ってキューを構築する

Here's a data-structure I use almost every day. It's an implementation¹ of a queue. 
You have two stacks, an in-stack and an out-stack. To add a new item, push it onto the 
in-stack. To remove an item, take the top item off the out-stack; if the out-stack's 
empty, push all the items on the in-stack onto the out-stack in reverse order and then 
take the top item.

ここにわたしがほぼ毎日使っているデータ構造があります。
それはキューの実装です。
in-stack と out-stack という二つのスタックがあります。
新しいアイテムを追加するには in-stack にアイテムをプッシュします。
アイテムを削除するには out-stack のトップのアイテムを取り除き、
もし out-stack が空であれば in-stack のアイテムすべてを逆順で out-stack に
プッシュしてからトップのアイテムを取り除きます。

In C++:

#ifndef QUEUE_H
#define QUEUE_H

#include <stack>
#include <iostream>

// This code brought to you by 10yo Talisker

template <class T>
class ts_queue
{
	private:
		std::stack<T> in;
		std::stack<T> out;
		void turnover();
		void turn_back_over();
		void dump_stack(std::stack<T>& stack);
	public:
		void push(T);
		void pop();
		int size();
		T& front();
		T& back();
		bool empty() const;
		void dump(); // dump output state, for debugging
};

template <class T>
void ts_queue<T>::turnover()
{
	// sample implementation, O(n)
	while (!in.empty()) {
		out.push(in.top());
		in.pop();
	}
}

template <class T>
void ts_queue<T>::turn_back_over()
{
	// sample implementation, O(n)
	while (!out.empty()) {
		in.push(out.top());
		out.pop();
	}
}

template <class T>
void ts_queue<T>::push(T t)
{
	in.push(t);
}

template <class T>
void ts_queue<T>::pop()
{
	if (out.empty()) {
		turnover();
	}
	out.pop();
}

template <class T>
int ts_queue<T>::size()
{
	return in.size() + out.size();
}

template <class T>
T& ts_queue<T>::front()
{
	if (out.empty()) {
		turnover();
	}
	out.top();
}

template <class T>
T& ts_queue<T>::back()
{
	if (in.empty()) {
		turn_back_over();
	}
	in.top();
}

template <class T>
bool ts_queue<T>::empty() const
{
	return in.empty() && out.empty();
}

// A couple of debugging functions, non-standard

template <class T>
void ts_queue<T>::dump_stack(std::stack<T>& st)
{
	using namespace std;
	stack<T> temp;
	while (!st.empty()) {
		cout << st.top() << " ";
		temp.push(st.top());
		st.pop();
	}
	while (!temp.empty()) {
		st.push(temp.top());
		temp.pop();
	}
	cout << endl << endl;
}

template <class T>
void ts_queue<T>::dump()
{
	std::cout << "in:  ";
	dump_stack(in);
	std::cout << "out: ";
	dump_stack(out);
}

// The rest of the std::queue API is left as an exercise for the reader

#endif

略

■_

■_

え。あれで終わり?


一つ前へ 2011年2月(下旬)
一つ後へ 2011年3月(中旬)

ホームへ


リンクはご自由にどうぞ

メールの宛先はこちらkbk AT kt DOT rim DOT or DOT jp