ときどきの雑記帖 めぐりあい電脳空間編


一つ前へ 2010年8月(上旬)
一つ後へ 2010年8月(下旬)






■_ State of the Lambda (Java)

疲れた。 ちょっと前のものですが。

State of the Lambda

State of the Lambda

Brian Goetz, 6 July 2010

This is an updated proposal to add lambda expressions (informally, "closures") 
to the Java programming language. This sketch is built on the straw-man proposal made 
by Mark Reinhold in December 2009.

これはプログラミング言語 Javaに λ式 (informally には“クロージャ”) を追加しようという
提案のアップデートです。この sketch は 2009年12月 の Mark Reinhold による
straw-man proposal を基にしています。

1. Background; SAM classes
   背景 SAM クラス群

The Java programming language already has a form of closures: anonymous inner classes. 
There are a number of reasons these are considered imperfect closures, primarily:

プログラミング言語Javaにはすでに無名インナークラスという form of closures があります。
これらが不完全なクロージャー (imperfect closure) であると見なされる幾つかの理由があります。

    * Bulky syntax

    * Inability to capture non-final local variables

    * Transparency issues surrounding the meaning of return, break, continue, and 'this'

      return, break, continue, 'this' の意味に関連する trasparency issues

    * No nonlocal control flow operators

It is not a goal of Project Lambda to address all of these issues.

これらの問題 (issues) すべてに対処するのは Project Lambda の目標ではありません。

The standard way for Java APIs to define callbacks is to use an interface representing 
the callback method, such as:

Java API でコールバックを定義するための標準的な方法は、コールバックメソッドを表現する

public interface CallbackHandler { 
    public void callback(Context c);

The CallbackHandler interface has a useful property: it has a single abstract method. 
Many common interfaces and abstract classes have this property, such as Runnable, 
Callable, EventHandler, or Comparator. We call these classes SAM classes.

この CallbackHandler インターフェースは一つの抽象メソッドを持っているという有用な性質
を持っています。Runnable や Callable、EventHandler、Comparator のような多くのコモンイ
ンターフェースと抽象クラスがこの性質を持っていて、わたしたちはこれらのクラス群を SAM 
クラス群 (SAM classes) と呼んでいます。

The biggest pain point for anonymous inner classes is bulkiness. To call a method 
taking a CallbackHandler, one typically creates an anonymous inner class:

無名インナークラスの最大の問題点はその冗長性 (bulkiness) です。CallbackHandler を取る

foo.doSomething(new CallbackHandler() { 
                    public void callback(Context c) { 

The anonymous inner class here is what some might call a "vertical problem": 
five lines of source code to encapsulate a single statement.

この無名インナークラスは一行の文を encapsulate するためにソースコード が5行になるという
"vertical problem" (垂直問題?) とでも呼べるようなものです。

    Astute readers will notice that the syntax used for examples in this document 
    differ from that expressed in the straw-man proposal. This does not reflect a final 
    decision on syntax; we are still experimenting with various candidate syntax options.

    抜け目のない鋭い読者の方々はこのドキュメントにある例で使われている構文が the straw-man
    proposal で express されているそれと違うことに気がつくでしょう。これは構文についての
    final decision を反映したものではありません。わたしたちはまだ various candidate syntax
    options について experimenting しています。

2. Lambda expressions

Lambda expressions are anonymous functions, aimed at addressing the "vertical 
problem" by replacing the machinery of anonymous inner classes with a simpler 
mechanism. One way to do that would be to add function types to the language, but this 
has several disadvantages: - Mixing of structural and nominal types; - Divergence of 
library styles (some libraries would continue to use callback objects, while others 
would use function types).

λ式は名前を持たない無名の関数 (anonymous functions) で、無名インナークラス (anonymous 
inner classes) の machinery を単純な機構に置き換えることによって"vertical 
problem" に対処するのを目指したものです。それを行う一つの方法が言語に関数型を追加
することですが、これにはいくつか欠点 - Mixing of structural and nominal types;
(structural な型と nominal な型の混合) - があります: ライブラリスタイルの相違 (他のものは
しょう) がそれです。ですからわたしたちはコールバックオブジェクトのインスタンスを生成する
のをより容易にする path を採用することを代わりに選択したのです。

Here are some examples of lambda expressions:

{ -> 42 }

{ int x -> x + 1 }

The first expression takes no arguments, and returns the integer 42; the second takes 
a single integer argument, named x, and returns x+1.

最初のλ式は引数がなく、整数の 42を返すものです。二番目のλ式は x という名前を持った整
数の引数を一つ取り x+1 を返すものです。

Lambda expressions are distinguished from ordinary statement blocks by the presence of 
a (possibly empty) formal parameter list and the -> token. The lambda expressions 
shown so far are a simplified form containing a single expression; there is also a 
multi-statement form that can contain one or more statements.

λ式と通常の文のブロックとは、(空の可能性もある) 仮引数リストと->トークンの存在によって
区別されます。この λ式は単一の式を含んだ単純化されたフォームですが、二つ以上の文を含むこと

3. SAM conversion
   SAM 変換

One can describe a SAM type by its return type, parameter types, and checked exception 
types. Similarly, one can describe the type of a lambda expression by its return type, 
parameter types, and exception types.

ある SAM type はその戻り値の型や、パラメータの型、checked exception の型によって説明で
きます。同様に、λ式の型をその戻り値の型やパラメータの型、chekced exception の型によっ

Informally, a lambda expression e is convertible-to a SAM type S if an anonymous inner 
class that is a subtype of S and that declares a method with the same name as S's 
abstract method and a signature and return type corresponding to the lambda 
expressions signature and return type would be considered assignment-compatible with S.

もしある無名の内部クラスが S の subtype であり、S の抽象メソッドと同じ名前を持ったメソッ
いて S に対して assignment-compatible であると見なされるのであれば、inforlmally には ある
λ式 e は SAM type S に対して convertible です。

The return type and exception types of a lambda expression are inferred by the 
compiler; the parameter types may be explicitly specified or they may be inferred from 
the assignment context (see Target Typing, below.)

λ式の戻り値の型と例外の型はコンパイラーによって inferred されます。そのパラメーターの型は
explicitly に指定されるかもしれませんし、代入文から inferred されるかもしれません
(後述の Target Typing を参照してください)。

When a lambda expression is converted to a SAM type, invoking the single abstract 
method of the SAM instance causes the body of the lambda expression to be invoked.

λ式が SAM タイプに変換されるときには、その SAM インスタンスの一つだけある抽象メソッド
を起動することで λ式の本体が起動されます

For example, SAM conversion will happen in the context of assignment:

たとえば代入のコンテキストで SAM 変換が起きるでしょう:

CallbackHandler cb = { Context c -> System.out.println("pippo") };

In this case, the lambda expression has a single Context parameter, has void return 
type, and throws no checked exceptions, and is therefore compatible with the SAM type 

この場合、λ式は single Context パラメーターと void return type を持っていてチェックされて
いない例外を送出するので、SAM タイプの CallbackHandler と互換性があります。

4. Target Typing

Lambda expressions can only appear in context where it will be converted to a variable 
of SAM type; the type of 'this' inside the lambda expression is (a subtype of) the SAM 
type to which the lambda expression is being converted. So the following code will 
print "Yes":

λ式は SAM 型の変数へと変換されるであろうコンテキストでのみ現れることが可能です。
λ式の内側にある 'this' の型はそのλ式が変換されるであろう SAM 型 (の subtype) です。

Runnable r = { ->
                 if (this instanceof Runnable)

The following use of lambda expressions is forbidden because it does not appear in a 
SAM-convertible context:

次のようなλ式の使用は拒絶 (forbidden) されます。なぜなら、このλ式が SAM-convertible な

Object o = { -> 42 };

In a method invocation context, the target type for a lambda expression used as a 
method parameter is inferred by examining the set of possible compatible method 
signatures for the method being invoked. This entails some additional complexity in 
method selection; ordinarily the types of all parameters are computed, and then the 
set of compatible methods is computed, and a most specific method is selected if 
possible. Inference of the target type for lambda-valued actual parameters happens 
after the types of the other parameters is computed but before method selection; 
method selection then happens using the inferred target types for the lambda-valued 

の検査によってinferred されます。これはメソッドセレクションにおける some additional 
complexity  を伴って (entails) います。すべてのパラメーターの型は ordinarily に演算され、
それから互換メソッド (compatible methods) の集合が演算されて、もし可能であればもっとも
specific なメソッド (most specific method) が選択されます。
lambda-valued された 実引数に対するターゲットの型の inference は、他のパラメータの型が
lambda-valued parameters に対してinferred されたターゲットの型を使って行われます。

The type of the formal parameters to the lambda expression can also be inferred from 
the target type of the lambda expression. So we can abbreviate our callback handler as:

ですからわたしたちはコールバックハンドラーを次のように abbreviate できるのです:

CallbackHandler cb = { c -> System.out.println("pippo") };

as the type of the parameter c can be inferred from the target type of the lambda

パラメーターの型として c はこのλ式のターゲットの型に影響を受ける可能性があります。

Allowing the formal parameter types to be inferred in this way furthers a desirable
design goal: "Don't turn a vertical problem into a horizontal problem." We
wish that the reader of the code have to wade through as little code as possible
before arriving at the "meat" of the lambda expression.

この方法で inferred される formal parameter types を許すことで
desirable な設計上の目標
"Don't turn a vertical problem into a horizontal problem."
を further します:
We wish that
the reader of the code have to wade through as little code as possible

before arriving at the "meat" of the lambda expression.

The user can explicitly choose a target type by specifying a type name. This might be
for clarity, or might be because there are multiple overloaded methods and the
compiler cannot correctly chose the target type. For example:

This might be for clarity, or might be
because there are multiple overloaded methods
and the compiler cannot correctly chose the target type.

executor.submit(Callable<String> { -> "foo" });

If the target type is an abstract class, it is an open question as to whether we want
to permit an argument list so a constructor other than the no-arg constructor can be

it is an open question as to
whether we want to permit an argument list
それは引数リストを許すのを望むかどうかという open question ですから、
so a constructor other than the no-arg constructor can be used.

5. Lambda bodies

In addition to the simplified expression form of a lambda body, a lambda body can also 
contain a list of statements, similar to a method body, with several differences: the 
break, return, and continue statements are not permitted, and a "yield" 
statement, whose form is similar to to the return statement, is permitted instead of a 
return statement. The type of a multi-statement lambda expression is inferred by 
unifying the type of the values yielded by the set of yield statements. As with method 
bodies, every control path through a multi-statement lambda expression must either 
yield a value, yield no value, or throw an exception. Expressions after a yield 
statement are unreachable.

す。メソッド本体と同様ですがいくつかの違いがあります: break, return, continue といった 
statements は許可されず、return 文の代わりにreturn 文と同様の書式を持った "yield"
文が許可されます。複数の文を持ったλ式の型はyield 文の set によって yield された値の型
の unifying によってinferred されます。メソッド本体と同じく、マルチステートメントのλ
式を通るすべての control path はyield value するか yield no value するかあるいは throw 
an exception のいずれかをしなければなりません。yield 文の後におかれている式は 
unreachable (到達不可能) です。

The complete syntax is given by:


lambda-exp := "{" arg-list "->" lambda-body "}"
arg-list := "(" args ")" | args
args := arg | arg "," args
arg := [ type ] identifier
lambda-body := expression | statement-list [ ";" ]
statement-list := statement | statement ";" statement-list

6. Instance capture

Once the target type of a lambda expression is determined, the body of a lambda 
expression is treated largely the same way as an anonymous inner class whose parent is 
the target type. The 'this' variable refers to the SAM-converted lambda (whose type is 
a subtype of the target type). Variables of the form OuterClassName.this refer to the 
instances of lexically enclosing classes, just as with inner classes. Unqualified 
names may refer to members of the SAM class (if it is a class and not an interface), 
or to members of lexically enclosing classes, using the same rules as for inner 

あるλ式のターゲットの型が決定されれば、あるλ式の本体はその親が target type であるよ
うな内部クラスとほぼ同様な方法で扱われます。この 'this' 変数は SAM-convert された 
(target の型の subtype であるような型を持つ) λを参照します。OuterClassName.this とい
う形式の変数は lexically にクラスをエンクローズしているインスタンスを内部クラスに対す
るかのように参照します。非修飾名 (unqualified name) はその SAMクラスのメンバー (それが
クラスでありインターフェースでなければ) やlexically に enclosing しているクラスを参照

For members of lexically enclosing instanaces, member capture is treated as if the
references were desugared to use the appropriate "Outer.this" qualifier and
Outer.this is captured as if it were a local final variable.

lexically に enclose しているインスタンスのメンバーのためのメンバーのキャプチャは
あたかもそのリファレンスが 適切な  "Outer.this" qualifier を使うために
desugared されて扱われます。そして、それがローカルでfinal な変数であるかのように 
Outer.this はキャプチャされます

7. Local variable capture

The current rules for capturing local variables of enclosing contexts in inner classes
are quite restrictive; only final variables may be captured. For lambda expressions
(and for consistency, probably inner class instances as well), we relax these rules to
also allow for capture of effectively final local variables. (Informally, a local
variable is effectively final if making it final would not cause a compilation failure.)

内部クラスにおける enclosing contexts にあるローカル変数のキャプチャリングについての
現時点でのルールは quite restrictive で、final 変数だけがキャプチャー可能です。
λ式 (と一貫性のため、おそらくは内部クラスのインスタンスも含まれます) に対して、
we relax these rules to also allow for capture of effectively final local variables.
めます (Informally, あるローカル変数はそれをfinal にしてもコンパイルの失敗を引き起こさ
ないのなら effectively final です)。

It is likely that we will not permit capture of mutable local variables. The reason is
that idioms like this:

わたしたちはmutable なローカル変数のキャプチャを許可しない方向にあります。

int sum = 0;
list.forEach({ Element e -> sum += e.size(); });

are fundamentally serial; it is quite difficult to write lambda bodies like this that
do not have race conditions. Unless we are willing to enforce (preferably statically)
that such lambdas not escape their capturing thread, such a feature may likely cause
more trouble than it solves.

というものが根本的には直列 (serial) であり、このような形でありながら競合条件を持たない
λ本体を書くことは非常に難しいからです。わたしたちがそのような λがキャプチャをするスレ

8. Exception transparency

A separate document on exception transparency proposes our strategy for amending
generics to allow abstraction over thrown checked exception types.

9. Method references

SAM conversion allows us to take an anonymous method body and treat it as if it were a
SAM type. It is often desirable to do the same with an existing method (such as when a
class has multiple methods that are signature-compatible with Comparable.compareTo().)

SAM conversion は無名のメソッドの本体を take して、それをあたかも SAM type
It is often desirable to do the same with an existing method
既存のメソッドと同一のことをすることはしばしば desirable なことです
(such as when a class has multiple methods that are signature-compatible with Comparable.compareTo().)
あるクラスが Comparable.compareTo() とsignature-compatible な
mltiple メソッドを持ったときのような

Method references are expressions which have the same treatment as lambda expressions 
(i.e., they can only be SAM-converted), but instead of providing a method body they 
refer to a method of an existing class or object instance.

メソッドリファレンスは λ式と同じ扱いを受ける式ですが (i.e., they can only be SAM-converted)、

For example, consider a Person class that can be sorted by name or by age:

たとえば名前や年齢によってソート可能なPerlson クラスを考えてみましょう:

class Person {
    private final String name;
    private final int age;

    public static int compareByAge(Person a, Person b) { ... }

    public static int compareByName(Person a, Person b) { ... }

Person[] people = ...
Arrays.sort(people, #Person.compareByAge);

Here, the expression #Person.compareByAge is sugar for a lambda expression whose 
formal argument list is copied from the method Person.compareByAge, and whose body 
calls Person.compareByAge. This lambda expression will then get SAM-converted to a 

ここで #Person.compareByAge という式は、メソッド Person.compareByAge からコピーされた
形式引数リストを持ち、Person.compapreByAge を呼び出す本体を持っているλ式に対する砂糖 
(sugar for a lambda expression) です。このλ式はそのあと Comparator へと SAM-coverted 

If the method being referenced is overloaded, it can be disambiguated by providing a 
list of argument types:

もしこのメソッドが overloaded された referenced であったなら
引数型のリストを提供することにより disambiguated できます:

Arrays.sort(people, #Person.compareByAge(Person, Person));

Instance methods can be referenced as well, by providing a receiver variable:

インスタンスメソッドはレシーバー変数 (receiver variable)を提供することによって

Arrays.sort(people, #comparatorHolder.comparePersonByAge);

このケースでは、implicit lamda expression が"comparatorHolder" の参照の 
final copy を capture し、その本体が receiver として使って comparePersonByAage を 
invoke します。

We may choose to restrict the forms that the receiver can take, rather than allowing 
arbitrary object-valued expressions like "#foo(bar).moo", when capturing 
instance method references.

のような arbitrary な object-valued expression を許すのではなくレシーバーが受け取れる

10. Extension methods

A separate document on defender methods proposes our strategy for extending existing
interfaces with virtual extension methods.

■_ 本日の巡回から




例の本が見当たらないでござる。 ってまあ工学社の本を置いているところを通らないというのが大きいのですが。

■_ まくろ

引数に2を与えると 0x1f、 3を与えると 0xf、 4を与えると 7、 5を与えると 3、 6を与えると 1 を出力するようなマクロを書きたいと思った。

1 0000_0000
2 110y_yyyy  5  (8 - 1 - 2)
3 1110_yyyy  4  (8 - 1 - 3)
4 1111_0yyy  3  (8 - 1 - 4)
5 1111_10yy  2  (8 - 1 - 5)
6 1111_110y  1  (8 - 1 - 6)


~(~0 << (8 - 1 - 2))
~(~0 << (8 - 1 - 3))
~(~0 << (8 - 1 - 4))
~(~0 << (8 - 1 - 5))
~(~0 << (8 - 1 - 6))

■_ メイドさん

あそびにいくヨ! 守礼皇18号 
24 風の谷の名無しさん@実況は実況板で [sage] 2010/08/18(水) 23:09:00 ID:EskYINODP Be:

26 風の谷の名無しさん@実況は実況板で [sage] 2010/08/18(水) 23:11:36 ID:OffF+QwgP Be:

29 風の谷の名無しさん@実況は実況板で [sage] 2010/08/18(水) 23:21:15 ID:EskYINODP Be:

30 風の谷の名無しさん@実況は実況板で [sage] 2010/08/18(水) 23:27:57 ID:jaOhAARr0 Be:

32 風の谷の名無しさん@実況は実況板で [sage] 2010/08/18(水) 23:36:53 ID:OffF+QwgP Be:



39 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 00:25:10 ID:78Q1buvN0 Be:

44 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 01:04:42 ID:MuHHFGy70 Be:

45 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 01:15:34 ID:MuHHFGy70 Be:

48 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 01:30:44 ID:hEi6bzSIO Be:


49 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 01:37:46 ID:7CkHVej4P Be:

50 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 01:41:03 ID:J8c66idE0 Be:

51 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 01:50:02 ID:8OPZ+pirP Be:


53 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 02:00:48 ID:8OPZ+pirP Be:

54 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 02:12:21 ID:MuHHFGy70 Be:

55 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 02:34:09 ID:XZ413QjS0 Be:

56 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 02:40:36 ID:diAwIwjp0 Be:

57 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 02:47:51 ID:MuHHFGy70 Be:

60 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 03:24:07 ID:sKTT5Svt0 Be:

63 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 03:49:08 ID:nNf2YxYf0 Be:

67 風の谷の名無しさん@実況は実況板で [] 2010/08/19(木) 07:43:00 ID:qQ00bL5L0 Be:

76 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 10:57:13 ID:MuHHFGy70 Be:

77 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 11:39:09 ID:/GI0XO8z0 Be:

78 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 11:48:56 ID:8OPZ+pirP Be:


82 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 14:07:25 ID:MuHHFGy70 Be:

83 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 14:19:38 ID:8OPZ+pirP Be:

101 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 17:51:30 ID:hEi6bzSIO Be:

106 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 18:18:09 ID:+EddQtCs0 Be:

108 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 18:23:13 ID:tqgZvuszP Be:

112 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 18:49:55 ID:hEi6bzSIO Be:

120 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 21:09:32 ID:yFbAPYkX0 Be:

124 風の谷の名無しさん@実況は実況板で [sage] 2010/08/19(木) 22:23:28 ID:hEi6bzSIO Be:

最近はグリーンベレーとかは流行らないのだろうか。 MASTER キートンよみてー

■_ ムーアの法則

Clojure ネタなんですが、実はポイントはそこではなくて

The Clean Coder: Why Clojure?

The Clean Coder

Why Clojure?

I have recently become quite an enthusiast for the language Clojure.  But why?  Why 
would someone who has spent the last 30 years programming in C, C++, Java, C#, and 
Ruby suddenly become enamored with a language that has roots that go back to 1957, i.e. 

During my first few decades as a professional programmer, I never learned Lisp.  I had 
heard of it, of course; though mostly in derisive terms.  People sneered about it with 
names like "Lots of InSignificant Parentheses".  So my view was not 
particularly favorable.


Moore's Law

Why is functional programming important?  Because Moore's law has started to falter.  
Not the part of the law that predicts that the number of transistors on a chip doubles 
every two years.  Thankfully, that part of the law seems to still be in effect.  The 
part that faltered is the part that says the speed of computers doubles every two 

なぜ関数プログラミングが重要なのか? それは、ムーアの法則(Moore's law) が falter
有効のままであるようです。faltered している部分というのはコンピューターの実行速度が

What this means is that our computers can still get faster, but only if we put multiple
CPUs on a chip.  This is why we've seen all these multi-core processors showing up.  And
that means that programs that need greater speed will have to be able to take advantage
of the multiple cores.


If you've ever written multi-threaded code, the thought of eight, sixteen, thirty-two, 
or even more processors running your program should fill you with dread.  Writing 
multi-threaded code correctly is hard!  But why is it so hard?  Because it is hard to 
manage the state of variables when more than one CPU has access to them.



And this is where functional programming comes in.  Functional programming, of the 
kind shown in SICP, is a way to write code that does not manage the state of variables, 
and could therefore be partitioned to run in parallel on as many processors as you 
like ‐ at least in theory.  In practice it might not be quite that trivial; but one 
thing is certain.  Moving functional programs to massively parallel system will be 
easier than moving non-functional programs.

And this is where functional programming comes in.
そしてこれが、関数プログラミングが comes in してきた理由です。
Functional programming, of the kind shown in SICP,
is a way to write code that does not manage the state of variables, 
and could therefore be partitioned to run in parallel on as many processors as you like
‐ at least in theory.

In practice it might not be quite that trivial; but one thing is certain.
Moving functional programs to massively parallel system will be easier than moving non-functional programs.



The last few decades have seen us migrate from procedures to objects.  Now the 
physical constraints of our hardware is  driving us to make a similar kind of paradigm 
shift towards functional languages.  The next few years will see us experiment with 
many different projects using those languages as we try to figure out which functional 
languages are best.  I fully expect Clojure to be ranked very highly when the results 
of those experiments come in.

最近の数十年でわたしたちは手続きからオブジェクトへの migrate を目にしてきました。
なるでしょう。わたしは、そのような実験が行われた際には Clojure がかなり上位に来るもの

Awesome Inc. template by Tina Chen. Powered by Blogger.

The part that faltered is the part that says the speed of computers doubles every two years.

やっぱり二年ごとに二倍になってますね。 18ヶ月でというのは日本生まれの誤解?

■_ What are the best languages for getting into functional programming?

What are the best languages for getting into functional programming? - Quora

What are the best languages for getting into functional programming?

Looking for a language with clear syntax, active community involvement, good 
documentation, etc.

On a meta-note, a great way to get into the general concept of functional programming 
is to dabble in several languages so that the abstract patters come into the 

Adam Smith • Insert a dynamic date here

Cannot add comment at this time.
Answer Summary
Many people think Haskell is the best language for getting into functional programming. 
 The community is good and it takes functional programming "to its logical 

Scheme also deserves special mention, due to its long history as a teaching language, 
and the correspondingly rich quality of its instructional materials.

Other choices (bold for choices with > 1 person supporting them):

    * F#
    * Clojure

    * Scala
    * OCaml/SML
    * Erlang



■_ 本日の巡回から




聴く InfoQ: Smaltalk's Dave and Erlang's Joe on Software Quality and Craftsmanship



Make it work first, then make it better

Make it work first, then make it better

Sometimes, worse is better. As strange as it may look, having something that is not 
perfect may be better than spending the time to make it perfect. This happens in many 
areas, and its the main reason perfectionists never get any work done. If the 
expectation is for perfection, then it is really hard to complete anything, because 
most of what we do is imperfect by necessity.

ときとして worse is better (劣っていることがよいこと *1) であることがあります。奇妙に
浪費するよりもずっと良いことかもしれません。これは多くの領域 (areas) で起こっているこ
とですが、その主な理由は perfectionists never get any work done (完璧主義者は決して仕
事を完了することがない) だからです。もしこの expectation が perfection のためのものな
らば、本当に何かをやり遂げることは困難です。なぜならわたしたちが necessityによって行う
ことの大半は不完全 (imperfect) だからです。

*1 → UNIX哲学 - Wikipedia

In software, however, there is an extra dimension to this problem. Because, the closer 
to perfection we get in a software application (in terms of features) the more code 
needs to be written and maintained. More code also means more bugs, which have the 
power to move us even further away from perfection.

しかしソフトウェアには、この問題に対する extra dimention があります。なぜならば、(in 
terms of features で) ソフトウェアアプリケーションを完全なものに近づけるためには、記述

Given the complexity of writing perfect software, it is just better to admit that we 
can’t write perfect programs. Instead, a more attainable goal is to write the minimum 
necessary to satisfy our requirements, while maintaining a good control of the overall 

記述することができないということを受け入れる (admit) のに just better です。なにより、
完全なプログラムを記述するのではない、より attainable な目標とはわたしたちの要求を満足
するのに必要最低限 (minimum necessary) なものを書くということです

Writing as few code as possible has several advantages that contribute to the quality 
of the resulting programs:

可能な限り少ないコードで書くことには、resulting programs の質に貢献する幾つかのアドバ

It is easier to test: every extra line of code is a new place where errors may be 
hiding. Why increasing that chance? Just write as few lines as you can and avoid 
potential problems

コードの extra line のそれぞれが、エラーがそこに潜んでいる可能性のある new place です。

Avoid unnecessary repetitions: a guiding principle of programming is the DRY method: 
Don’t Repeat Yourself. While trying to write as few code as possible you will see 
more opportunities to avoid unnecessary repetitions.

プログラミングにおける a guiding principle が DRY (Don't Repeat Yourself) メソッドです。

Performance: usually, less code leads to better performance. This is particularly true 
for modern software, where one of the main limitations is processor cache size (as 
opposed to main memory size). Small programs that solve the problem without requiring 
huge class libraries may have a big advantage in the performance arena.

小さなプログラムは、パフォーマンスの arena において big advantage を得るかもしれません。

It is not always easy to write small programs though. Remember the old saying: “I 
wrote a large book because I didn’t have the time to make it small”… The same apply 
to programs. It is sometimes easier to copy and paste previous code, or code that was 
mindlessly taken from some other project or from the web. It is harder to think about 
the overall problem and adapt the code to your situation.

Remember the old saying:
“I wrote a large book because I didn't have the time to make it small”…
同じことをプログラムにも適用します。以前のコードや、他のプロジェクトや web から 
mindlessly にとってきたコードをコピペすることことが容易なこともあります。問題全体につ

What about making it fast? Well, it turns out that making programs fast is more a 
matter of design than of good programming skills. It is futile to change a program to 
yield better performance if the structure of the program is not created with this in 
mind. And once you get the big picture of the software design, getting small 
improvements in speed is not that interesting. There are exceptions to this rule; for 
example, video games can use small speed gains to give much improved user experience.

プログラムを高速化することについてはどうでしょうか? まず、プログラムを高速にすることは
グラムの構造がこの考えに基づいて作られていないもの (not created with this in mind) で
あるのなら、よりよいパフォーマンスを yield するためにプログラムを変更することは futile 
(無駄、無益)なことです。そして一度このソフトウェアの設計に関する big picture を理解でき
れば、スピードの点において小規模な改良を gett することがinteresting ではなくなるでしょ
う。このルールには例外が存在していて、たとえばビデオゲームではユーザーの体験 (user 
experience) を大きく向上させるためにわずかな高速化を行うことがあります。

So, you see that writing small programs has a lot of virtues. And, despite this, it is 
a difficult task, because it requires a lot of thinking in advance.

でもそれは、難しい task でもあります。
なぜならそれが a lot of thinking in advance を要求しているからです。

Developers are most of the time pressed to think less and finish more lines of code.
But it pays the time to look for good solutions before you enter code into your preferred IDE.

開発者は、考える時間を少なくする一方でコードを増やしています。しかし、お気に入りの IDE 

■_ 文字列比較

仮に、入力が UTF-8 (を使った Unicode)だったりすると BM (やKMP)だと ナイーブな実装では表がでっかくなる(おお、また文字集合と表の問題だ)から 避けたのかなあと言う気も。あと、多バイトで表す場合も面倒があったり性能の低下 があるんじゃなかったかなあ(Ruby も確かこの辺りの理由でBMを使ってません)。








でこの StringImpl 見てて思ったんだけど、 これメモリもうちょいケチれね?

本日のツッコミ(全3件) [ツッコミを入れる]

_ Rui (2010-08-18 07:37)

WebKitのstrstrは確かに面白いけどBMより遅そうではないですか? なぜBMを使わないのか謎です。

_ もわ (2010-08-18 09:02)




_ shinh (2010-08-18 12:30)

今 BM の説明読みました。メモリ使用量かなーと思いましたがどうでしょうね。 WebKit の場合

JS はあまり好きじゃないですけど、アプリケーションに組み込む用途の言語としては Python 
とか Ruby よりは向いてるんじゃないですかねたぶん。理由はたぶん、

- Ruby とか Python のスレッドモデルとかを強制されない方がいい
- メモリ使用量とか少ない方がいい
- 組み込み関数とか多すぎない方がいい
- シンプルな機構の方がいい
- プロトタイプベース
- 実装がたぶん高速

あたりで。つまりたぶん lua とかでもいいわけですけど。 


/trunk/JavaScriptCore/wtf/text/StringImpl.cpp – WebKit
size_t StringImpl::find(const char* matchString, unsigned index)
512	{
513	    // Check for null or empty string to match against
514	    if (!matchString)
515	        return notFound;
516	    unsigned matchLength = strlen(matchString);
517	    if (!matchLength)
518	        return min(index, length());
520	    // Optimization 1: fast case for strings of length 1.
521	    if (matchLength == 1)
522	        return WTF::find(characters(), length(), *(const unsigned char*)matchString, index);
524	    // Check index & matchLength are in range.
525	    if (index > length())
526	        return notFound;
527	    unsigned searchLength = length() - index;
528	    if (matchLength > searchLength)
529	        return notFound;
530	    // delta is the number of additional times to test; delta == 0 means test only once.
531	    unsigned delta = searchLength - matchLength;
533	    const UChar* searchCharacters = characters() + index;
534	    const unsigned char* matchCharacters = (const unsigned char*)matchString;
536	    // Optimization 2: keep a running hash of the strings,
537	    // only call memcmp if the hashes match.
538	    unsigned searchHash = 0;
539	    unsigned matchHash = 0;
540	    for (unsigned i = 0; i < matchLength; ++i) {
541	        searchHash += searchCharacters[i];
542	        matchHash += matchCharacters[i];
543	    }
545	    for (unsigned i = 0; i < delta; ++i) {
546	        if (searchHash == matchHash && equal(searchCharacters + i, matchString, matchLength))
547	            return index + i;
548	        searchHash += searchCharacters[i + matchLength];
549	        searchHash -= searchCharacters[i];
550	    }
551	    if (searchHash == matchHash && equal(searchCharacters + delta, matchString, matchLength))
552	        return index + delta;
553	    return notFound;
554	}

おそらくこのアルゴリズムでいいんじゃないかと思います (ついった経由ですでに shinh さんには伝えてたりしますが) → ラビン-カープ文字列検索アルゴリズム - Wikipedia

で、Ruby でこのアルゴリズムを使っていると思われる辺り。 1.8だともっと単純なんですが、1.9ではエンコーディングによる場合分けがあったりして ちょっと複雑。

static inline long
rb_memsearch_ss(const unsigned char *xs, long m, const unsigned char *ys, long n)
    const unsigned char *x = xs, *xe = xs + m;
    const unsigned char *y = ys, *ye = ys + n;
#ifndef VALUE_MAX
# if SIZEOF_VALUE == 8
# elif SIZEOF_VALUE == 4
# endif
    VALUE hx, hy, mask = VALUE_MAX >> ((SIZEOF_VALUE - m) * CHAR_BIT);

    if (m > SIZEOF_VALUE)
	rb_bug("!!too long pattern string!!");

    	/* Prepare hash value */
    for (hx = *x++, hy = *y++; x < xe; ++x, ++y) {
	hx <<= CHAR_BIT;
	hy <<= CHAR_BIT;
	hx |= *x;
	hy |= *y;
    /* Searching */
    while (hx != hy) {
	if (y == ye)
	    return -1;
	hy <<= CHAR_BIT;
	hy |= *y;
	hy &= mask;
    return y - ys - m;

static inline long
rb_memsearch_qs(const unsigned char *xs, long m, const unsigned char *ys, long n)
    const unsigned char *x = xs, *xe = xs + m;
    const unsigned char *y = ys;
    VALUE i, qstable[256];

    /* Preprocessing */
    for (i = 0; i < 256; ++i)
	qstable[i] = m + 1;
    for (; x < xe; ++x)
	qstable[*x] = xe - x;
    /* Searching */
    for (; y + m <= ys + n; y += *(qstable + y[m])) {
	if (*xs == *y && memcmp(xs, y, m) == 0)
	    return y - ys;
    return -1;

static inline unsigned int
rb_memsearch_qs_utf8_hash(const unsigned char *x)
    register const unsigned int mix = 8353;
    register unsigned int h = *x;
    if (h < 0xC0) {
	return h + 256;
    else if (h < 0xE0) {
	h *= mix;
	h += x[1];
    else if (h < 0xF0) {
	h *= mix;
	h += x[1];
	h *= mix;
	h += x[2];
    else if (h < 0xF5) {
	h *= mix;
	h += x[1];
	h *= mix;
	h += x[2];
	h *= mix;
	h += x[3];
    else {
	return h + 256;
    return (unsigned char)h;

static inline long
rb_memsearch_qs_utf8(const unsigned char *xs, long m, const unsigned char *ys, long n)
    const unsigned char *x = xs, *xe = xs + m;
    const unsigned char *y = ys;
    VALUE i, qstable[512];

    /* Preprocessing */
    for (i = 0; i < 512; ++i) {
	qstable[i] = m + 1;
    for (; x < xe; ++x) {
	qstable[rb_memsearch_qs_utf8_hash(x)] = xe - x;
    /* Searching */
    for (; y + m <= ys + n; y += qstable[rb_memsearch_qs_utf8_hash(y+m)]) {
	if (*xs == *y && memcmp(xs, y, m) == 0)
	    return y - ys;
    return -1;

rb_memsearch(const void *x0, long m, const void *y0, long n, rb_encoding *enc)
    const unsigned char *x = x0, *y = y0;

    if (m > n) return -1;
    else if (m == n) {
	return memcmp(x0, y0, m) == 0 ? 0 : -1;
    else if (m < 1) {
	return 0;
    else if (m == 1) {
	const unsigned char *ys = y, *ye = ys + n;
	for (; y < ye; ++y) {
	    if (*x == *y)
		return y - ys;
	return -1;
    else if (m <= SIZEOF_VALUE) {
	return rb_memsearch_ss(x0, m, y0, n);
    else if (enc == rb_utf8_encoding()){
	return rb_memsearch_qs_utf8(x0, m, y0, n);
    else {
	return rb_memsearch_qs(x0, m, y0, n);

qs ってなんの略だろう? s は sequence な気もするけれど。

■_ 日本語版には原著にない章もあるそうで

O'Reilly Japan - Books :: New and Upcoming

O'Reilly Japan - Books :: New and Upcoming
Title	ISBN	定価	発売日
Android Hacks 	978-4-87311-456-9 	\3,990 	2010年08月
iPhone/iPadゲーム開発ガイド 	978-4-87311-462-0 	\2,940 	2010年09月
言語設計者たちが考えること 	978-4-87311-471-2 	\3,780 	2010年09月
初めてのプログラミング 第2版 	978-4-87311-469-9 	\2,100 	2010年09月



Masterminds of Programming - O'Reilly Media

Full Description

Masterminds of Programming features exclusive interviews with the creators of several 
historic and highly influential programming languages. In this unique collection, 
you'll learn about the processes that led to specific design decisions, including the 
goals they had in mind, the trade-offs they had to make, and how their experiences 
have left an impact on programming today. Masterminds of Programming includes 
individual interviews with:

    * Adin D. Falkoff: APL
    * Thomas E. Kurtz: BASIC
    * Charles H. Moore: FORTH
    * Robin Milner: ML
    * Donald D. Chamberlin: SQL
    * Alfred Aho, Peter Weinberger, and Brian Kernighan: AWK
    * Charles Geschke and John Warnock: PostScript
    * Bjarne Stroustrup: C++
    * Bertrand Meyer: Eiffel
    * Brad Cox and Tom Love: Objective-C
    * Larry Wall: Perl
    * Simon Peyton Jones, Paul Hudak, Philip Wadler, and John Hughes: Haskell
    * Guido van Rossum: Python
    * Luiz Henrique de Figueiredo and Roberto Ierusalimschy: Lua
    * James Gosling: Java
    * Grady Booch, Ivar Jacobson, and James Rumbaugh: UML
    * Anders Hejlsberg: Delphi inventor and lead developer of C#




■_ 今日の晒しあげ

未経験にほど近いプログラマ新人です。 | OKWave


JAVA ファイル分割(バイナリ)のプログラムを早急に作らなくてはいけなくなりました。





丸投げ自体はありふれたものであっていまさら驚くものでもないけど、 「新人です」「作らなければならなくなりました」 ってあたりの表現を考えると社会人ぽいですよねえ。 仕事の丸投げ?



Perl 6 subroutines and home made operators

Perl 6 subroutines and home made operators

Welcome back to the Perl 6 Tricks and Treats

This time together with a Perl 6 screencast to show the thought operator and the +- 
operator of Perl 6. Direct link to the Perl 6 subroutines screencast

This entry was first sent out as part of the Perl 6 Tricks and Treats. Visit here to 

It was also included the Perl 6 series of screencasts.

The Thought operator

I just tried the thought operator in Perl 6. Typed in this:

  "szabgab" .oO "Perl 6 is cool";

and got the following:

  szabgab thinks Perl 6 is cool

The +- operator

I also tried the +- operator:

  2.78  ~~ 10 +- 3 ?? 't' !! 'f'     # f
  7.5   ~~ 10 +- 3 ?? 't' !! 'f'     # t
  13    ~~ 10 +- 3 ?? 't' !! 'f'     # t
  13.1  ~~ 10 +- 3 ?? 't' !! 'f'     # f

I think you get the point here. We check if the value on the left is between 10 +- 3.

~~ is the smart match operator, ?? !! are the two parts of the ternary operator of 
Perl 6 and +- is, well not everyone has the +- or the thought operator but if you read 
on you'll see how you can create one for yourself.

Subroutines in Perl 6
Perl 6におけるサブルーチン

Subroutines in Perl 6 are declared using the sub keyword just as in Perl 5 But in Perl 
6, after the name of the subroutine one can provide a signature, describing the 
parameters that function accepts.

Perl 6におけるサブルーチンは、Perl 5と同様に sub キーワードを使って宣言できますが、
Perl 5とは違いサブルーチン名の後ろに、その関数が受理するパラメータを説明する

    use v6;

    sub f($a, $b) {
        return "$a - $b";

    say f(4, 2);

If called with a different number of arguments then Perl will issue an error message:
違う個数の引数でもって呼び出した場合、Perl はエラーを出力します

    say f(4, 2, 5);

gives this message:

    Too many positional parameters passed; got 3 but expected 2
      in 'f' at line 3:script.p6
      in main program body at line 8:script.p6


    say f(4);

gives this message:

    Not enough positional parameters passed; got 1 but expected 2
      in 'f' at line 3:script.p6
      in main program body at line 8:script.p6

Perl 5 style in Perl 6

For people who really want the Perl 5 style subroutine declaration they can use this code:
Perl 5形式でも記述できますよと。

    use v6;
    sub f {
        return @_.perl
    say f(4, 2);     # [4, 2]
    say f(4);        # [4]
    say f(4, 2, 3);  # [4, 2, 3]

but that would eliminate all the nice features of Perl 6.

Optional parameter

What if we would like to allow the user to pass 1 or 2 parameters? For that case we 
can mark the second parameter as optional:

    use v6;
    sub f($a, $b?) {
        return defined $b ?? "$a - $b" !! "$a - na";
    say f(4, 2);    # 4 - 2
    say f(4);       # 4 - na

The ?? !! is a the ternary operator of Perl 6 so what we see above is that if $b is 
defined the "$a - $b" is returned and when $b is not defined then 'na' will 
be returned instead of that value.

?? || は Perl 6における三項演算子 (ternary operator) で、上記の例では $b が
define されていれば $a - $b が返され、$b が define されていなければ
何かの値の代わりに 'na' が返されます。

Parameters are read-only

In other cases you might be tempted to replace $b with some default value like this:

    use v6;
    sub f($a, $b?) {
        $b //= 17;
        return defined $b ?? "$a - $b" !! "$a - na";
    say f(4, 2);    # 4 - 2
    say f(4);       # 4 - na

but this will throw an exception like this:

    Cannot modify readonly value
      in '&infix:<=>' at line 1
      in 'f' at line 4:02.p6
      in main program body at line 8:02.p6

as arguments in Perl 6 are by default read only;
のように、Perl 6におけるパラメータはデフォルトでリードオンリーです。

Default value of a parameter

There are two solutions to this, depending on what do you really want to achieve: If 
you only want to give a default value to $b then the best way is to add it right in 
the signature:

    use v6;
    sub f($a, $b = 17) {
        return defined $b ?? "$a - $b" !! "$a - na";
    say f(4, 2);    # 4 - 2
    say f(4);       # 4 - 17

In this case you don't even need the question mark '?' as the presence of a default 
value automatically makes the parameter optional. This still keeps $b read-only within 
the subroutine.

Making the parameter a copy and thus changeable

The other solution is to mark the $b variable as a 'copy' of the original value. 
Therefore allowing the user to make changes to it:

    use v6;
    sub f($a, $b? is copy) {
        $b //= 17;
        return defined $b ?? "$a - $b" !! "$a - na";
    say f(4, 2);    # 4 - 2
    say f(4);       # 4 - 17

Type restrictions on parameters

We can also restrict the parameters of a subroutine to certain data types:

    use v6;
    sub f($a, Int $b) {
        return "$a - $b";
    say f(4, 2);
    say f(4, "foo");

The first call will succeed but the second will generate an exception:

    4 - 2
    Nominal type check failed for parameter '$b'; expected Int but got Str instead
      in 'f' at line 4:03.p6
      in main program body at line 9:03.p6

Other constraints on parameters

It is also possible to provide further constraints on the parameters:

    use v6;
    sub f($a, Int $b where { $b < 10 }) {
        return "$a - $b";
    say f(4, 2);
    say f(4, 11);

    4 - 2
    Constraint type check failed for parameter '$b'
      in 'f' at line 4:03.p6
      in main program body at line 9:03.p6

Creating operators in Perl 6

There are of course a lot of other aspects for subroutine definition in Perl 6 but 
let's now go back to our original goal, to create the +- operator.

So how can one create a new operator in Perl 6? It is quite simple as an operator is 
just a subroutine with a funny way of calling it.

So here is how to create the thought operator. We create a subroutine, declaring it to 
be an infix operator with the name .oO

    sub infix:<.oO>($name, $thought) {  
        say "$name thinks $thought"

Specifically we want to make +- an infix operator that create a Range. Not something 
complex. Within the angle brackets we put the new operator, the sub has a signature of 
two scalars and within the block we put actual code that needs to be executed.

    sub infix:<+->($a, $b) { ($a-$b) .. ($a+$b) }

Then we can use

   5 +- 2

that will create the range 5-2 .. 5+2 also known as 3 .. 7


もうひとつ Perl 6

blog | Perlgeek.de :: The State of Regex Modifiers in Rakudo

Mon, 16 Aug 2010

The State of Regex Modifiers in Rakudo

Permanent link

During the last one and a half month, I've been working on making regex modifiers 
easily available in Rakudo.

The regex compiler itself has to support only a few of the adverbs that can be applied 
to regexes; those include :ignorecase, :sigspace, :ignoremark and :continue/:pos. 
NQP-rx, the regex engine that Rakudo uses under the hood, supports those (except 
:ignoremark), so previously you could write

if 'ABC' ~~ /:i abc/ {
    say "case insensitive match";

But not

if 'ABC' ~~ rx:i/abc/ {
    say "case insensitive match";

nor m:i/abc/, for that matter.

I've patched Rakudo to actually recognize those adverbs outside of the regex, and also 
for s/// substitutions.

Another category of adverbs are those that apply to regex calls, not to the 
compilation of a regex. Among those are :global/:g, :overlap/:ov, :nth($n), :x. I've 
implemented those for substitutions, but implementing them for m// turns out to be 
quite a bit harder.

The reason is the return value: each regex match returns a Match object, which can 
store positional and named parts. S05 says that regex matches with multiple results 
should return a single match object, with all results as positional parts. It can be 
distinguished from a normal match object by evaluating it in slice context... which 
Rakudo doesn't support yet.

Now the subst method and thus s/// are implemented by calling .match(:global, ...), 
and without slice context, it can't distinguish between multiple matches, and a single 
match with subcaptures. And so my changes to the global match broke the substitution, 
and I see no easy way to fix it.


Copyright 2008, 2009: Moritz Lenz
This page may be used under the terms of the Creative Commons Attribution 3.0 Germany License. Please place a link to the pages you use for your derivative work.
Layout based on YAML, powered by mowyw and blosxom

修飾子の置き方は定まらないなあ。前のほうに置くというのは変えないみたいだけど (まあこっちのがわかりやすくはある)。


  • ASCII.jp:価格性能比に優れたK7でシェアを伸ばしたAMD|ロードマップでわかる!当世プロセッサー事情
  • オラクル/グーグル/Javaの嵐についてJames Goslingが語る - karasuyamatenguの日記
  • 株式会社サイエンス社 株式会社新世社 株式会社数理工学社
  • TEMPLE Home Page [OS-9]
  • 津野田興一『世界史読書案内』 - あとで書く
  • Lispは受入れられないLispだ - taro-nishino の日記
  • リチウムイオン電池、韓国企業が一気に台頭、半導体や液晶パネルの「二の舞い」になると危惧する声も : SIerブログ
  • 言葉と文章とプログラムと: たわごと
  • 【ELIS復活祭(その1)】「若い人にLISPの技術を伝えたい」,伝説のLISPマシン「ELIS」のイベントが開催 - ものづくりとIT - Tech-On!
  • コミックマーケット78 3日目反省会レポート | 橋本充電中
  • Smalltalkをやるでござる - とあるクソ院生の夏休み
  • 2010年08月16日


    最近のベビーカーってずいぶんしっかりとして、サイズも大きいものばかりなんですね。 まあそれはそれでいいんですが、あるとき路線バスに一度に三台乗ってきたときには えらい大変でした(多分二台くらいまでしか想定してない)。 昔よく見た折りたたみのなんてのはやわで危ないから使えないってことなんでしょか。


    ■_ Cool クラス?

    Cool クラスとはなにか。

    blog | Perlgeek.de :: What is the "Cool" class in Perl 6?
    What is the "Cool" class in Perl 6?
    In Perl, subroutine and operator names determine what happens, usually not the type of 
    the arguments. Instead the arguments are coerced to a type on which the operation 
    makes sense:
    say uc 34;      # coerces 34 to a string, and upper-cases it
                    # 34 を文字列化してから大文字にする
    say 1 + "2";    # converts "2" to a number before adding
                    # 加算の前に "2" を数値に変換する
    To make things more extensible, the uc function re-dispatches to the uc method on its 
    argument. So for the example above to work, we need an uc function in Int. And in 
    Array, so that @a.uc works. And so on.
    より extensible にするために、uc 関数はその引数に対する uc メソッドに
    The original approach was to stuff all these methods into Any, the base class of the 
    object hierarchy. Which kinda worked, but also meant that all user-defined classes 
    ended up having some few hundreds methods to start with. Not good.
    These days, the type Cool fills this niche: most built-in types (all that are meant to 
    be used in that polymorphic way) inherit from Cool, so the uc method is actually 
    defined in class Cool, coerces to string, and then re-dispatches to the internal logic 
    that actually does the upper-casing.
    The name either stands for Convenient object oriented loopback, or just expresses that 
    that most built-ins are cool with an argument of that type.
    # Cool → Convenient object oriented loopback
    If users want to write a type that can be used like a built-in type now just inherit 
    from Cool, and define coercion methods to other built-in types. If the types don't 
    inherit from Cool, they are more light-weight, and less magic. There's more than one 
    way to do it.
    Cool is a class (and not a role), because classes are mutable; so if you want to 
    inject behavior into nearly all built-in types, augmenting Cool is an option (though 
    usually considered evil, and should not be done lightly).

    ■_ どの Lisp がいいのでしょうか

    reddit に訊け。

    What is your favourite lisp and why? : lisp
    I've been a programmer for the last 8 years and have developed a love for learning new 
    languages; the syntax differences, low-level implementations and everything to do with 
    new technology is what drives me to learn a new way of thinking. My path's taken me 
    through PHP, JS, Erlang, Haskell, C and the basics of Java and now I'm turning to Lisp. 
    I've toyed with Clojure and loved the syntax and expressiveness of it however didn't 
    like it's reliance on Java.
    Which lisp does everyone recommend and why? Should I see clojure through or is Scheme 
    and CommonLisp just as good if not better for being mature?
    皆が薦める Lisp はどれで、それはなぜでしょうか?
    Scheme や Common Lisp があまり向いていないことを確認してから clojureを
    All the lisps you mentioned are good. None are perfect.
    あなたの挙げた Lisp (の仲間) はすべて良いものです。
    Clojure is modern, fits its technological and cultural environment well, and packages 
    recent ideas from functional programming in an especially elegant way. But it relies 
    on the jvm (a demerit if you don't like it), and its type system needs work (though, 
    to be fair, that work is happening).
    I find that, with the use of the leiningen build tool, almost all of the pain caused 
    by the java infrastructure is alleviated.
    Common lisp is great in that it packages up thirty years of what working programmers 
    considered to be essential tools for getting things done quickly. Admittedly, they did 
    the packaging almost thirty years ago, so an awful lot of it seems quaint, arcane, or 
    gratuitously complicated. Still, if you grit your teeth and acclimate yourself, the 
    result is a language with which you can accomplish a great deal with a modest effort, 
    and one that imposes very few arbitrary barriers. Its status as a hoary old standard 
    means that there are a bunch of good implementations, and its age means that a handful 
    of them have been maintained since before half the programmers in the world were born, 
    so they're not likely to disappear any time soon.
    Be mindful of common lisp's age and the fact that its users are provincial. CL seems 
    weird and gratuitously different when you first approach it, and the locals aren't 
    always friendly to outsiders. Live there for a while and it alters your brain so that, 
    after a while, you begin to see the world from the CL point of view, and outsiders 
    start to look strange and unappealing to you.
    Scheme's pivot is finding a language whose essential abstractions are so powerful that 
    it doesn't need to have a lot of features. You can learn it very quickly, especially 
    if you like all-encompassing abstractions. The power of scheme's abstractions in 
    intoxicating, and they make you wonder why every language doesn't simply build on 
    scheme's tools.
    But that focus on smallness and elegance means that for decades of its life scheme has 
    not had a decent story around libraries. That, combined with the power of its 
    abstractions, means that there are fifty different mutually incompatible libraries for 
    doing anything whatsoever.
    There are a few schemes that ease that problem, providing rich sets of libraries, if 
    you are willing to commit to a particular implementation.
    But my favorite lisp is Ralph, the scheme+clos variant invented at apple computer, 
    that later evolved into Dylan. Sadly, Ralph is extinct.
    Common Lisp. It's a standard, and there are multiple high quality implementations 
    available, both free and commercial. Also has excellent documentation, and mountains 
    of sample code available to help you learn.
    But in my opinion, 8 years for all those languages is not enough time, and unless 
    you're much brighter than me (quite possible...) you run the risk of mere dabbling.
    Lisp macros on Erlang VM; complete access to Erlang OTP modules.
    Documentation is rather poor, though. I'd like to fix that, if I can ever find time...
        * I like 3-Lisp because it has another Lisp underneath Lisp, and then another and 
          another ...
        * I like Lisp Machine Lisp because the frame buffer is just another array and the 
          console is the value of the console variable
        * I like Logo because I can drive the turtle around
        * I like LispWorks because it travelled further into space than any other Lisp. On 
          board of the space craft Deep Space 1.
        * I like InterLisp because it does what I mean.
    R, because it is lisp without s-expressions http://dan.corlan.net/R_to_common_lisp_translator/




    ■_ ぼちぼち

    マルチバイト文字用のアルゴリズムというかロジックをどうにかしないと いけない状況になってきたような。でも現状の glibc のでもそんなに速度低下 したんだっけか。

    GNU awk very slow with multibyte locale and long strings
    GNU awk very slow with multibyte locale and long strings
    From: 	Davide Brini
    Subject: 	GNU awk very slow with multibyte locale and long strings
    Date: 	Sun, 15 Aug 2010 14:40:24 +0100
    Hi Arnold, all
    It was brought to my attention on IRC the following thread:
    the results of which seem to indicate that GNU awk performance gets worse
    linearly with the increase in string size, even with such a simple test
    I can reproduce the results on my system (with locale en_GB.utf8, gawk 3.1.8).
    As mentioned in the thread, GNU awk is the only one that supports multibyte
    locales, and some tracing shows that in the test case it spends almost all
    the time calling mbrtowc(). This is with a UTF-8 locale.
    Indeed, if the tests are repeated with LC_ALL=C, GNU awk is very fast in
    both cases.
    I don't know if this is expected behavior, but I thought it would be good
    to report it anyway.

    で蒸気の文面にあるリンク先を見てみると、 スレッドが結構伸びているのだけどとりあえず問題のものだけ

    [dev] off topic - awk versions performance comparison from Joseph Xu on 2010-08-11 (dev mail list archive)
    [dev] off topic - awk versions performance comparison
    Hi everyone,
    I was playing around with awk and ran into some surprising data for the
    function match(s, r), which returns the position of the first match of
    regular expression r in string s. Here's the test I ran:
    $ yes | head -10000 | tr -d '\n' >/tmp/big
    $ yes | head -1000000 | tr -d '\n' >/tmp/bigger
    $ time awk '{for (i=1; i < 100; i++) { match($0, "y")} }' /tmp/big
    real 0m0.056s
    user 0m0.053s
    sys 0m0.000s
    $ time awk '{for (i=1; i < 100; i++) { match($0, "y")} }' /tmp/bigger
    real 0m5.695s
    user 0m5.140s
    sys 0m0.553s
    The difference is almost exactly 100x, which is the size difference
    between the input files. It seems ridiculous that the amount of time
    taken to match the first character of a string grows linearly with the
    size of the string. The time it takes to load the contents of the file
    does not contribute significantly to this increase.
    That was GNU awk. Trying p9p awk:
    $ time 9 awk '{for (i=1; i < 100; i++) { match($0, "y")} }' /tmp/big
    real 0m0.024s
    user 0m0.023s
    sys 0m0.000s
    $ time 9 awk '{for (i=1; i < 100; i++) { match($0, "y")} }' /tmp/bigger
    real 0m1.856s
    user 0m1.857s
    sys 0m0.000s
    This is a lot faster compared to GNU awk but there's still a 77x
    difference between the two input files.
    #p9p ってなんだろ?
    #こちらでも gawk ほどではないにしても70倍以上の差が。
    Finally, trying Kernighan's One True Awk (from
    $ time nawk '{for (i=1; i < 100; i++) { match($0, "y")} }' /tmp/big
    real 0m0.001s
    user 0m0.000s
    sys 0m0.000s
    $ time nawk '{for (i=1; i < 100; i++) { match($0, "y")} }' /tmp/bigger
    real 0m0.015s
    user 0m0.010s
    sys 0m0.003s
    The time difference here is actually only due to loading a larger file:
    $ time nawk '{ }' /tmp/big
    real 0m0.001s
    user 0m0.000s
    sys 0m0.000s
    $ time nawk '{ }' /tmp/bigger
    real 0m0.016s
    user 0m0.013s
    sys 0m0.003s
    So at least nawk's performance makes sense. To make things a little more
    confusing, I tried matching on a non-existent pattern:
    $ time awk '{for (i=1; i < 100; i++) { match($0, "z")} }' /tmp/big
    real 0m0.005s
    user 0m0.003s
    sys 0m0.000s
    $ time awk '{for (i=1; i < 100; i++) { match($0, "z")} }' /tmp/bigger
    real 0m0.085s
    user 0m0.080s
    sys 0m0.003s
    $ time 9 awk '{for (i=1; i < 100; i++) { match($0, "z")} }' /tmp/big
    real 0m0.006s
    user 0m0.003s
    sys 0m0.000s
    $ time 9 awk '{for (i=1; i < 100; i++) { match($0, "z")} }' /tmp/bigger
    real 0m0.077s
    user 0m0.077s
    sys 0m0.000s
    $ time nawk '{for (i=1; i < 100; i++) { match($0, "z")} }' /tmp/big
    real 0m0.007s
    user 0m0.007s
    sys 0m0.000s
    $ time nawk '{for (i=1; i < 100; i++) { match($0, "z")} }' /tmp/bigger
    real 0m0.612s
    user 0m0.607s
    sys 0m0.003s
    Now GNU awk and p9p awk are showing on the order of 10x differences
    between the two files, while nawk shows 100x difference. Obviously the
    regex algorithm that nawk uses is different from the other two, and
    there's a trade off here, though nawk still looks superior.
    Last test:
    $ echo -n 'z' >>/tmp/big
    $ echo -n 'z' >>/tmp/bigger
    Now the pattern does match, but at the very end of the string.
    $ time awk '{for (i=1; i < 100; i++) { match($0, "z")} }' /tmp/big
    real 0m0.056s
    user 0m0.057s
    sys 0m0.000s
    $ time awk '{for (i=1; i < 100; i++) { match($0, "z")} }' /tmp/bigger
    real 0m5.861s
    user 0m5.270s
    sys 0m0.590s
    $ time 9 awk '{for (i=1; i < 100; i++) { match($0, "z")} }' /tmp/big
    real 0m0.057s
    user 0m0.057s
    sys 0m0.000s
    $ time 9 awk '{for (i=1; i < 100; i++) { match($0, "z")} }' /tmp/bigger
    real 0m4.760s
    user 0m4.756s
    sys 0m0.000s
    $ time nawk '{for (i=1; i < 100; i++) { match($0, "z")} }' /tmp/big
    real 0m0.007s
    user 0m0.007s
    sys 0m0.000s
    $ time nawk '{for (i=1; i < 100; i++) { match($0, "z")} }' /tmp/bigger
    real 0m0.612s
    user 0m0.610s
    sys 0m0.003s
    In this case all the numbers make sense, assuming a linear scan is going on.
    Can someone shed some light on these vastly different numbers? Why do
    GNU awk and p9p awk perform so poorly on the easy case where they just
    have to match the first character? 

    One ture awk は、utf-8のみ対応とかいう感じじゃなかったっけ? ちょっとフェアな比較ではないような気も。 いずれにしても現状のあのマッチングアルゴリズムは改善の余地ありだろうなあ。

    せっかく shiro さんが話題を広げてくれたのにそれに乗っかった話を 書いている時間がががが。



    ここ何週間か連続して土曜日にイベントが続くなあ(よろしくないものも含めて○| ̄|_)

    ■_ Evolution of a Groovy programmer


    gist: 524018 - GitHub
    Evolution of a Groovy programmer.groovy #
    // Newbie programmer
    // 新米
    int factorial_newbie(int n) {
        if (n == 0) {
            return 1
        } else {
            return n * factorial_newbie(n - 1)
    println factorial_newbie(6)
    // First year programmer, studied Pascal
    // Pascalを習得済みの一年生
    int factorial_pascal(int n) {
        int result = 1;
        for (int i = 1; i <= n; i++) {
            result = result * i;
        return result;
    println factorial_pascal(6)
    // First year programmer, studied C
    // Cを習得済みの一年生
    int fact_c(int n) {
        int result = 1;
        for (int i = 1; i <= n; i++) {
            result *= i;
        return result;
    println fact_c(6)
    // First year programmer, SICP
    // SICPを(ry
    int fact_sicp(int n, int acc=1) {
        if (n > 1) {
            return (fact_sicp((n - 1), (acc * n)))
        } else {
            return (acc)
    println fact_sicp(6)
    // First year programmer, Python
    int Factorial_python(int n) {
        int res = 1
        (2..n).each { i ->
            res *= i
        return res
    println Factorial_python(6)
    // Lazy Groovy programmer
    int fact_lazy(int n) {
        return (n <= 1) ? 1 : n * fact_lazy(n - 1)
    println fact_lazy(6)
    // Lazier Groovy programmer
    def fact_lazier = { (it <= 1) ? 1 : it * call(it - 1) }
    println fact_lazier(6)
    // Groovy expert programmer
    def fact_expert = { n -> n ? (1..n).inject(1, { a, b -> a * b }): 1 }
    println fact_expert(6)
    // Unix programmer
    def factorial_unix(int n) {
        def command = "factorial " + n
        def proc = command.execute()
        print proc.in.text
    // Web designer
    // Web デザイナー
    String factorial_web(int n) {
          --- Code snippet from The Math Vault ---
          --- Calculate factorial (C) Arthur Smith 1999 ---
        String result = Integer.toString(1);
        int i = 1 //Thanks Adam
        while (i <= n) {
            //result = result * i; //It's faster to use *=
            //result = Integer.toString(result * result + i)
               //result = Integer.parseInt(result *= i) #??????
            result = Integer.toString(Integer.parseInt(result) * i)
            //result = new String(Integer.parseInt(result) * i)
            i = i + 1;
        return result
    println factorial_web(6)
    // Windows programmer
    // Windows プログラマー
    def CalculateAndPrintFactorialEx(dwNumber,
                                     dwReserved) {
        if (lpsscSecurity != null) {
            return null; // Not implemented
        int dwResult = 1;
        for (int dwCounter = 1; dwCounter <= dwNumber; dwCounter++) {
            dwResult *= dwCounter;
        return 1;
    CalculateAndPrintFactorialEx(6, System.out, null, null, null, null)
    // Enterprise programmer
    // 大企業に勤めるプログラマー?
    class InternalBase {
        private int base
        public InternalBase(Integer base) {
            this.base = base.intValue()
        int getBase() {
            return new Integer(base)
    class StandardMathematicsSystem {
        private static StandardMathematicsSystem INSTANCE = null
        private Integer base
        private StandardMathematicsSystem(InternalBase base) throws RuntimeException {
            if (base.getBase().compareTo(new Integer(2)) != 0) {
                throw RuntimeException("Non base 2 bases are not supported.")
            this.base = base.getBase()
        int calculateFactorial(Integer target) {
            Integer result = new Integer(1)
            for (Integer i = new Integer(2); i.compareTo(target) <= 0; i = new Integer(i.intValue() + 1)) {
                result = result * i
            return result
        static private StandardMathematicsSystem createInstance(InternalBase base) {
            return new StandardMathematicsSystem(base)
        static StandardMathematicsSystem getInstance(InternalBase base) {
            if (INSTANCE == null) {
                INSTANCE = createInstance(base)
            return INSTANCE
    println StandardMathematicsSystem.getInstance(new InternalBase(new Integer(2))).calculateFactorial(new Integer(6))
    // CPU parsimonious programmer
    def factorial_cpu(int n) {
        def fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000, 6402373705728000, 121645100408832000, 2432902008176640000]
        return fact[n]
    println factorial_cpu(6)

    Evolution of a Groovy Programmer : programming

    ■_ 実装依存です


    正規表現 Part7 [chaika]
    408 デフォルトの名無しさん [sage] 2010/08/15(日) 14:26:57 ID: Be:
    409 デフォルトの名無しさん [sage] 2010/08/15(日) 15:12:35 ID: Be:
    410 408 [sage] 2010/08/15(日) 15:18:56 ID: Be:


    現在、改行コードを含めた任意の文字列を探す為に | OKWave

    対象となるコードが1バイト(つーかオクテット?)の範囲に収まるくらいなら、 ビットベクトルを使うのが多分常道で、その場合はどう書いても実行結果は同じのはず。 マルチバイト文字やらワイド文字やらUnicode なんかが対象に入ってくると これはもう実装次第としかいいようがないわけで。 仮に対象を Unicode としてその大きさがほぼ100万文字というパターンを考えると、 ビットベクトルでこれを収めるには…と。 まあイマドキの環境だったらどうってことないのかなあそれでも。

    んで、ワタクシが尊敬するプログラマーの一人であるところの serow さんが 日本語対応した jgawk だと 1バイトに収まる範囲についてはビットベクトルを使って、 マルチバイトを使う範囲はすなおにコードを並べてました。 \S や \s のようなメタ文字とは事情が違いますが、 このパターンだと並べ方によってマッチングのスピードに差が出る可能性がありますね。









        * ブースの立看板がBoogie Boardだらけという異常事態。ほんとうにみんなで示し合わせた
          ように、何処にいってももBoogie Board。
        * 買ったのは、「ラムダプラス(Haskell本)」「SPEを256倍使い倒すための本」「快楽的技
              o 最後のはThoughtWorks アンソロジーみたいな感じで、Unicode小話、Ruby ハンズオン
                (gitで取ってきてビルドするまで)、keyeva、まいんbot、Xlib プログラミング、
              o なんか執筆陣がピチピチ過ぎる気がする。まぶしい。
        * ショタケットアンソロジーの出来がすさまじくってビックリ。全年齢向け。これは買いです。

    ピンポイントで↑の本があった辺りだけ行ってきました。 もー半端でなく汗かいた。 んで、人の流れに乗っていったらなぜか東方関連のエリアにににに!


    買ったもの。 まずはチロルチョコサイズの、パッケージがアレなチョコレート (本当に食べられるものだそうです。帰り着くまでの暑さでこんなことにw)

    とっとと↑の用事は済んだので企業ブースへ行ってみました。 とりあえず欲しかったのは手に入りました。
    あ、電撃家で売ってるのを気がつかなかった「こんぱそのガジェットポーチ」があった ○| ̄|_


    ■_ 本日のネタ


    Twitter / みずのひろき: ボクの主観だとSchemeの記事にはshiroさん、 ...

    Smalltalk の記事には sumim さんとか。

    ■_ Wheeler jump

    http://visio.sc.niigata-u.ac.jp/s1008/2009s1008_06.pdf だと日本語の解説があるんですが、画像になっているらしく 必要なところだけ切り出すのがめんどー。 で、

    C++, Development Tools, Java, Open Source, Web... the world of software development from Dr Dobb's
    Early Calls
      Mar 15, 2008
          G     K   Pseudo-code: makes the assembler store the
                    address of the S F below in location 42.
                    The 3 θ below will therefore point beyond
                    this, at the T 1 F instruction.
          S     F   Subtract contents of location 0 from accumulator.
          G  3  θ   Jump to T 1 F if accumulator is negative.
          T     F   Transfer accumulator to location 0;
                    clear accumulator.
          T  1  F   Transfer accumulator to location 1;
                    clear accumulator.

    サブルーチンは一般に↑な形をしています。 調べるとわかるのですが、EDSAC にはスタックレジスターもありませんし、 サブルーチン呼び出しの命令もありません。 ではどのようにサブルーチンを呼び出し、そこから帰ってくるのか?

    If that's how subroutines were written, how did you call them? Using self-modifying 
    code. Suppose the instruction at location m+1 will jump to the subroutine which starts 
    at location n. Then at location m, you place an instruction that copies location m - 
    i.e. itself - into the accumulator. The first part of the subroutine picks this up and 
    massages it into an instruction that jumps to m+2, and then copies that instruction to 
    the end of the subroutine. This mechanism, I read from tributes to Wheeler, was known 
    as the "Wheeler jump". Here's an example: 
                        The code below calls the subroutine
                        that starts at n.
     m:     A  m   F    Add contents of location m into accumulator. This is the
                        current instruction, A m F.
     m+1:   G  n   F    Goto location n if accumulator negative.
                        It will be, because of how A m F is represented, so
                        this enters the subroutine at n.
                        The code below is the subroutine.
            G      K
     n:     A  3   F    Add 3 to accumulator. This contains A m F;
                        because of how instructions are represented, the
                        add converts it into E m+2, "goto m+2 if
                        accumulator non-negative".
     n+1:   T  p+2 θ    Transfer this goto instruction to location n+p+2;
                        clear accumulator.
     n+2:               First instruction of subroutine proper.
     n+p+1:             Final instruction of subroutine proper.
     n+p+2: Z      F    Becomes the goto.
        * Copyright © 2010 UBM TechWeb, All rights reserved.


    ■_ 本日の巡回から



    国会図書館で拾ってきたネタをひとつ。 アスキー創刊2号(1977年8月号)にあった記事なんですが、こんなのが

      書かれ、2キロバイトのタイニイ BASIC (TINY=小型)  から、
      12キロバイトもある拡張BASICなどがある。 半年ぐらい前は、
      ・TREC (Text REckonig and Compiling)
      また、VTLはVery Tiny Language のことで、わずか750バイトでス

    なんと APL の名前がこんなところにも! しかもポスト BASICの言語として!

    このコラム (アメリカマイコン事情)では少なくとも もう一回 APL がとりあげられていました。 残念ながら時間に余裕がなかったのでコピーをとったりできませんでした。 近いうちにまた行こうと目論んでいます。

    ■_ NULLの告白


    Qt Labs Blogs » Apology of the NULL pointer
    Apology of the NULL pointer
    #Apology 謝罪、弁明
    Posted by cduclos on Wednesday, August 11, 2010 @ 21:20
    “Nobody likes me. I'm despised everywhere I go. I am accussed of being the 
    responsible of many problems and even calamities. Some say that I am accursed. Some 
    even say that I am some kind of disease that needs to be cured. When people see me the 
    first thing they think is “oh no, not again…”. Nobody has a kind word for me. 
    People spends hours and hours finding ways to make sure that I am not welcomed. They 
    spend incredibly amounts of time looking for ways to avoid me, to squash me and to 
    make sure I cannot even get close. Even worst, some people has managed to make me 
    invisible to their eyes, so even if I appear they do not see me. If I manage to get 
    close and say “hi”, they do not say “hi” back to me. In fact, whenever I say 
    something people look at me very weirdly. People has been told since the beginning 
    that I am the worst thing that could ever happen to their software.
    I am accussed of being the responsible of many problems and even calamities.
    僕のことを accursed  (呪われたもの、始末におえないもの) だと呼ぶ人たちがいる。
    人々が僕を見て最初に考えることは “oh no, not again…”なのだ。
    Even worst,
      some people has managed to make me invisible to their eyes,
      so even if I appear they do not see me.
    If I manage to get close and say “hi”,
    they do not say “hi” back to me.
    In fact,
    whenever I say something people look at me very weirdly.
    皆は look at me very weirdly する。
    People has been told
    since the beginning 
    that I am the worst thing that could ever happen to their software.
    They do not understand me. And in fact I think nobody understands me. But that is ok, 
    because no matter what I will still be around after your software is done. I will 
    still be around when your software becomes outdated. In fact, you can count on me 
    being around all the time. And yet I'm not haunting you. If you just stopped for a 
    while and listened to my message, you will see that I can be your best friend. My 
    mission is very simple: if I appear in your software it is not a sign that your 
    software is badly designed, I'm just pointing out a case that was not considered 
    before. If you could just understand that sometimes it is much better that I come and 
    say “hi” than to close the door to me, you will realize that we can work together to 
    make your software the best software ever. So please, stop cursing me and for once try 
    to listen to my message.”
    because no matter what I will still be around after your software is done.
    I will still be around when your software becomes outdated.
    In fact, you can count on me being around all the time.
    And yet I'm not haunting you.
    If you just stopped for a while and listened to my message,
    you will see that I can be your best friend.
    if I appear in your software
    it is not a sign that your software is badly designed,
    I'm just pointing out a case that was not considered before.
    If you could just understand
    that sometimes it is much better
    that I come and say “hi” than to close the door to me,
    you will realize that we can work together to make your software the best software ever.
    So please, stop cursing me and for once try to listen to my message.”
    The text above was inspired by a conversation with some colleagues regarding when to 
    detect a NULL pointer and when simply let the software crash.

    ■_ それHaskellで

    Haskell で記述した Python 3とかなんとか。 インデントのあたりどう処理しているんだろう? あー、でもHaskellでHaskell書けてるわけだしなあ。

    berp: an implementation of Python 3, now in AUR (compiler and interpreter) | Arch Linux and Haskell
    berp: an implementation of Python 3, now in AUR (compiler and interpreter)
    Posted on August 13, 2010 by dons00	
    berp, is an implementation of Python 3, written in Haskell. It is now available in AUR.
    It provides a compiler and an interpreter. In both cases the input Python program is 
    translated into Haskell code. The compiler turns the Haskell code into machine code. 
    The interpreter runs the Haskell code immediately via the GHCi interpreter. The user 
    interface of the interpreter imitates the one provided by CPython.
    コンパイラーとインタープリターがあり、その両方ともが入力されたPython プログラムを
    Haskell のコードへ変換します。コンパイラーはそのHaskellコードをさらに機械語へ
    変換します。インタープリターは変換されたHaskellコードを GHCi インタープリター
    CPython によって提供されているものを imitate しています。
    For more information:
        * See the tutorial
        * The github home.

    reddit でも取り上げられています Berp: Python3 -> Haskell compiler; Produces self contained binaries : programming

    ■_ reddit に訊け!


    Language to learn in free time. : programming
    Hey guys, i'm going to be starting college in about a week and Im taking a Java class 
    (even though i'm already petty proficient in java). I know a little about C/C++ as 
    well. I was wondering what language you guys like to use in your free time as sort of 
    a fun break from the industry standards. Ive been looking into Python and Lisp but im 
    not set on one and dont know which to pick. thanks
    I'd vote for Clojure. It's a newer Lisp on the JVM with all sorts of cool stuff. You 
    wont be hurting for libraries, that's for sure.
    Some that seem topical:
        * Haskell is the most readable terse language I know. Many of its ideas are decades
          away from arriving in common practice. It will also keep you thinking and keep 
          you busy, and it's possible that it will change the way you think about programming. 
          It's very mind-expanding.
        * Perl 6 has some of the newest ideas I've seen. Getting into it now might not be 
          a bad idea since it is finally starting to be usable. You get an extremely powerful, 
          terse language for doing most any practical task. If you learn it, it will likely 
          become indispensible.
        * D would be good if you like the general territory you're already in, but think 
          that some aspects could be made better. D is an up-and-coming systems programming 
          language which attempts to do C++ right. I find it less gimmicky than Go, and less 
          likely to be abandoned, but it also looks like a nice language overall.
        * Clojure is also an extremely powerful functional programming language, and the 
          only one with an almost seamless bridge to Java's libraries. Clojure implements
          many interesting, easy-to-use and powerful parallelism techniques and couples
          them with Lisp's famous flexibility. The language also has what I personally
          consider one of the nicest standard libraries, incorporating lots of great stuff
          from the frontiers of FP (Haskell) as well as ordinary pragmatic programming.
    I personally use Python, but if your a Java guy Scala may be a good choice.
    I'm currently using OCaml for most of my hobby projects.
    Things I like about it:
       1. Strong typing - you won't be able to implicitly / accidentally use the wrong type
       2. Functional - this is the big plus for me right now - I'm currently learning
          functional programming and OCaml has been a nice introduction for me
       3. Imperative - for those times when functional code just doesn't quite cut it
       4. Object oriented - although I haven't really used the objects much yet
       5. Implicit (duck-) typing - most of the time you don't need to declare the type
          of your variable, the compiler works it out for you.
       6. Garbage collected - OCaml has a very fast garbage collector, which saves me
          having to worry about managing the memory myself.
       7. Pattern matching - This rocks! Pattern matching is like a switch statement on
          steroids, turbocharged, bigger and better than ever before!
    Things I don't like about OCaml:
       1. I feel that the syntax could be a bit nicer (prefacing labelled parameters with 
          ~ starts to look a bit messy after a while)
       2. Semi-colons - some times you need one, some times you don't, and other times you 
          need 2! - I've worked it out now, but it did take a while to get used to
       3. Functions have to be explicitly declared as recursive - I know the reasoning 
          behind this (its to do with the type checker) but it still seems strange for a 
          functional language
       4. Some of the standard library functions have quite long names - try printing a 
          string with some integers and you will see what I mean - string_of_int, 
          string_of_float, etc.
    However, OCaml has been a very interesting language to learn. It has helped me to 
    think about lots of problems in different ways, and quite a bit of this thinking can 
    be used in other languages like Python as well (in fact, my Python style has now 
    changed quite a bit).
    I'd vote for Python. I do embedded program (usually in C) for work so it's nice to use 
    something like Python for hobby type projects where I can get a lot done quickly. Lisp 
    seems somewhat antiquated from my experience. Then again, not many young folk are that 
    knowledgeable in C so you could distinguish yourself by getting 'kick ass' with it and 
    have a leg up in the ever expanding embedded programming world, which is mainly 
    dominated by self taught EEs. Plus, blinking LEDs is so much cooler than writing 
    "hello world"
        * If you don't know any dialect of Lisp yet, a Lisp. You need the experience of a 
          multi-purpose homoiconic language with a reduced set of axioms and syntax. For
          which I recommend Scheme, as a clean, FP-oriented Lisp.
        * If you want something arguably more practical, for some definitions of practical, 
          try Python, for a clean, dynamic, strong typed language where some/a lot of high
          level, fun ctional abstraction is possible (though not that much as the Python
          community is kinda stupid in this aspect).
        * If you know the basics of a Lisp, and want to use it in your everyday work, 
          maybe even slip a bit of it wherever they'll pay you, try Clojure.
        * If you want a more exotic language, try Haskell for a great FP language.
        * Maybe Erlang if you're interested in parallel systems.
        * Personally, I wouldn't bother with low-level ant work (C/C++) outside 
          bread-making. C sucks feature-wise, and C++ is insane and kinda sucks.
    Scala and Clojure.
    Learn Assembly. Write some non-trivial program with it. Most likely you will not need 
    it in the future, but it will give you a deep understanding of the machine, and it 
    will make you grateful when using high-level languages.
    Depending on what you are interested in, I would suggest either Ruby on Rails (if you 
    want to do some website work) or Python. Both are a pretty significant transition away 
    from Java/C++ but many concepts are still around and both are extremely easy to read 
    so you can look at code examples and pick it up extremely quickly. Both Ruby and 
    Python are used throughout industry and since most schools don't teach to them, having 
    a few independent projects on your resume can really boost your value and get you your 
    first summer internships, which can really get your foot in the door.
    If you want to use Lisp, I would suggest going for Clojure, since it's a modern and 
    high interest language right now. It runs on the JVM and allows you to use the Java 
    API which may aid you in transitioning.
    If you don't like that for some reason, Scheme. I would stay away from Common Lisp and 
    other dialects unless you have some reason to do otherwise (like you think you might 
    want to do research with some professor, and X dialect is what he or she uses).
    ruby on rails is not a language
    Ruby. It's look like English. Has wide standart library.Hell Community. Or pick up 
    clojure. It's becoming really hot now
    Python, Erlang.
    Learn Erlang, you will need both the functional part and the parallel part covered in 
    the future, at least if you are working with server side systems. If not then Python 
    is often a good choice.
    I prefer D and JavaScript for my side programming. D is much more powerful, but with 
    JavaScript you tend to see more results quicker. I haven't tried Haskell, Clojure, or 
    Scala yet. They seemed to be talked about a lot among non-mainstream language 

    いろいろな言語が出てますね~ (適当に抜き出したので、このほかにも名前があがっているものがあります)。

    ■_ 本日のネタひろい

    from マ板。

    405 仕様書無しさん [sage] 2010/08/12(木) 12:50:11 ID: Be:
        char *hoge(…){
         char ret[100];
         return ret;
    406 仕様書無しさん [sage] 2010/08/12(木) 17:09:04 ID: Be:
    407 仕様書無しさん [sage] 2010/08/12(木) 17:12:45 ID: Be:
    408 仕様書無しさん [sage] 2010/08/12(木) 17:39:27 ID: Be:
    409 仕様書無しさん [sage] 2010/08/12(木) 18:19:18 ID: Be:
    410 仕様書無しさん [sage] 2010/08/12(木) 18:33:42 ID: Be:
    411 仕様書無しさん [sage] 2010/08/12(木) 19:28:30 ID: Be:
    412 仕様書無しさん [sage] 2010/08/12(木) 20:38:00 ID: Be:
    413 仕様書無しさん [sage] 2010/08/12(木) 23:22:40 ID: Be:
    414 仕様書無しさん [sage] 2010/08/12(木) 23:25:56 ID: Be:
    415 仕様書無しさん [sage] 2010/08/12(木) 23:28:52 ID: Be:
    416 仕様書無しさん [sage] 2010/08/12(木) 23:28:58 ID: Be:
    417 仕様書無しさん [sage] 2010/08/12(木) 23:30:46 ID: Be:
        だから、char ret[]は、関数を抜けたら意味がなくなるのに、戻値として返してるとよろしくないじゃないか。
    418 413 [sage] 2010/08/12(木) 23:35:35 ID: Be:
    419 仕様書無しさん [sage] 2010/08/12(木) 23:42:34 ID: Be:
    420 仕様書無しさん [sage] 2010/08/12(木) 23:46:04 ID: Be:
    421 仕様書無しさん [sage] 2010/08/13(金) 00:36:49 ID: Be:
    422 仕様書無しさん [sage] 2010/08/13(金) 00:52:22 ID: Be:
    423 仕様書無しさん [sage] 2010/08/13(金) 01:19:23 ID: Be:
        Java や C# ばかりを相手にしてるとたまに C, C++ をさわったときに >>405 のパターンではまりそうで怖い
    424 仕様書無しさん [sage] 2010/08/13(金) 08:39:57 ID: Be:
        char *hoge(…){
        #if 1
        char *ret:
        ret = malloc(99+1);
        if ( ret != null ) {
         char ret[100];
        #if 1
         return ret;
    425 仕様書無しさん [sage] 2010/08/13(金) 08:43:11 ID: Be:
    426 仕様書無しさん [sage] 2010/08/13(金) 09:34:42 ID: Be:
        mallocした領域を返す関数には、名前に _alloc という接尾辞を付ける、という
        char* hoge_alloc() { ... }
        #define hoge_free(p) free(p) 
    427 仕様書無しさん [sage] 2010/08/13(金) 10:56:17 ID: Be:


    ■_ 本日の巡回から




    EDSAC Wheeler ジャンプ IBM 704 FORTRAN I



    即値と参照:基本的/本質的だと思うから再論 - 檜山正幸のキマイラ飼育記
    2005-09-01 (木)

    最初に見たときは call by refernce の「参照」を指していってると思ったのですが ちと違うかな? でも強引に話を call by reference やら call by value (by nameその他はとりあえず忘れて) にもっていきます。

    最古の実用の高水準言語(らしい)、FORTRAN のサブルーチン呼び出しは call by value ではなく call by reference です。 FORTRAN には「参照型」にするようなデータ型はありませんが (んー配列は微妙か?)、それでもデータ型によらず実引数ではアドレスが 渡されます(アドレスを渡すことと call by reference であることはまったく同一 ということではありませんがそれはそれ)。

    ということで、IBM 704 (最初にFORTRAN が実装されたコンピューター) やら EDSAC やら調べてたのですね。 EDSAC のサブルーチン呼び出しの手順はすごーく面白い(複雑)なので、 いっぺん見てみるといいと思います。 キーワードは「Wheeler ジャンプ」

    ■_ D


    InformIT: Interview with Andrei Alexandrescu (Part 1 of 3) >
    Interview with Andrei Alexandrescu (Part 1 of 3)
    From the author of The D Programming Language
    In part 1 of this three-part series, Eric Niebler talks with his pal and fellow 
    InformIT contributor Andrei Alexandrescu about the D programming language and Andrei's 
    new book about it: what makes D different from other languages, whether D's class 
    libraries rival those of Java and .NET, and why Andrei claims not to be a guru.
    Andrei: Yeah, Weasel was Enki 0.1. I remember how I did a search-and-replace changing 
    Weasel to Enki in the whitepaper. Heck, it's still online.
    Any language definition needs to deal with so much stuff, it ain't even funny. And as 
    it's all subjective and difficult to quantify, it's inevitable that some decisions 
    that seem good at one time look really crappy at others. Walter pointed out some 
    aspects of Enki that he knew from experience will age badly, and in fact were already 
    starting to suffer from conceptual rot. Instead of defining Enki from scratch and 
    probably straight into oblivion, Walter suggested, why not use D as a basis, a 
    starting point for a "better D" that I could help define?
    At that time I didn't like D—I found it unprincipled and derivative, in addition to 
    having serious expressiveness problems for certain designs. We agreed to work together 
    on these issues. And that's how D2 was born out of D1's rib: in two worn-out chairs in 
    a smoky bar (they still smoked in that bar back then!) over unbearable noise. Soon 
    thereafter, we started those legendary day-long meetings that often featured Bartosz 
    Milewski, you, and others.
    In order to shake off D1's mistakes, Walter decided to make D2 an incompatible branch 
    while putting D1 in maintenance mode. That gambit caused understandable protests 
    within the community, but has paid off immensely. Today, there are so many aspects of 
    D2 that make me think, "Wow, we really did here what had to be done"—most of 
    which would have been impossible if compatibility with D1 was a requirement.
    Eric: As a garbage-collected, natively compiled language, it seems to me that D stakes 
    out a very small patch of real estate on the computing landscape: not as fast as a 
    language with explicit memory management (C or C++), and not as flexible or portable 
    as a JIT-ed or interpreted language (C# or Java). In your opinion, is there enough 
    room in the niche D has chosen, especially considering that the niche is shrinking as 
    JIT performance improves and GC can be added to C++ as a library?
    Andrei: The question assumes two separate and definite choices: D is garbage-collected, 
    and D is natively compiled. In reality, they are both options: D also supports manual 
    memory-management (for example, you can call good old malloc() and free() without any 
    intervening translation layer), and a definite subset of D is JIT-able (although at 
    this time no JIT has been written for it). That doesn't make D restrict itself to a 
    small patch between other languages; instead, it invades the territory claimed by each. 
    Let me substantiate that claim below.
    Let's see what a language needs in order to be JIT-able:
        * It must be memory-safe. Virtually all JIT infrastructures today want to be able 
          to validate and sandbox code.
          memory-safe でなければなりません。今日のすべての JIT 命令はコードの validate と
          sandbox が可能であることが事実上求められています。
    #memory-safe って?
        * The language needs some means of dynamic binding and evaluation. This could be 
          done entirely as a library, as Java and C# libraries have shown.
          言語は動的束縛や動的評価 (dynamic binding and evaluation) の要素を必要とします。
          これは Java や C#のライブラリに見られるようにライブラリとして実現可能かもしれません。
    That leaves us with safety as the one core language feature necessary for JIT-ability. 
    But D isn't safe—it has unrestricted pointers (per my reference to malloc() and free() 
    above). D allows you the decadent joys of adult life—you can cast a pointer to an 
    integer and then back, if you really want to do that. If you want to punch a few 
    electrons down unusual backstreets, D will be your trusty sidekick.
    Eric: Has anybody worked out a way to access Java's or .NET's class libraries from D? 
    That would be interesting, and lessen the need for a vast D class library in the short 
    Andrei: Not that I've heard. There's only one .NET proof-of-concept implementation of 
    a D compiler. There's also talk about translating Java code into D automatically or 
    semi-automatically. Again, such things are not easy but are eminently feasible; market 
    forces will decide what happens.
    Eric and Andrei continue this discussion in "Interview with Andrei Alexandrescu (Part 2 of 3)."
    © 2010 Pearson Education, Informit. All rights reserved.
    800 East 96th Street, Indianapolis, Indiana 46240
    Informit Network

    ■_ People of Perl 6: Jonathan Worthington

    Jonathan Worthington って、Perl 6関連ではよく見る名前ですね。 最近専用のblogも始めていたような(それまでは perl.orgだかに間借りしていた)。

    People of Perl 6: Jonathan Worthington - Perl.com
    People of Perl 6: Jonathan Worthington
    By chromatic on August 11, 2010 3:29 PM 
    Jonathan Worthington is one of the lead developers of Rakudo Perl 6. A couple of 
    months before the Rakudo Star release, Perl.com interviewed him about his work on Perl 
    6 and what the rest of us should expect as we explore this new language. Follow 
    Jonathan's work at 6guts.
    What's your primary interest in Perl 6?
    At the moment, I'm primarily interested in writing a good compiler for it. Beyond that, 
    I'd like to use it to build more cool things, though I've little idea what yet. We'll 
    see what comes along.
    When did you start contributing to Perl 6?
    Back in 2003, a couple of years after discovering Perl, I heard about Perl 6. I found 
    the apocalypses engaging, and joined a couple of mailing lists. A lot of 
    perl6-language bewildered me. Well, some things never change. :-) I felt way out of my 
    depth on the language design front back then, but then found the Parrot project, which 
    was a little more concrete. I wrote a couple of patches to improve Windows support.
    What have you worked on?
    Well, not long after digging in to junctions, I discovered that doing junctions 
    properly meant doing multiple dispatch... and doing multiple dispatch meant doing a 
    bunch of the type system stuff... and doing that meant being able to declare classes 
    and roles. A couple of years of hacking later, and with plenty of input and help from 
    others, we're doing pretty well on all of those areas now in Rakudo. :-)
    What feature was your moment of epiphany with Perl 6?
    That's a hard one. There are many interesting features in Perl 6—some of them big 
    things, some of them much smaller. What I've really come to admire isn't so much the 
    features themselves, but rather the much smaller number of fundamentals that they're 
    all built on top of, and how they them form a coherent whole that is greater than its 
    What makes a feature or a technique "Perlish"?
    It makes an easy thing easy, or a hard thing possible. The amount of code is 
    proportional to the task at hand. It feels natural. It solves a real, practical 
    problem, so you can get your work done efficiently and have time to go for a beer.
    What does Rakudo need for wider deployment?
    Wider deployment means growing the users base. People should choose a technology 
    primarily on the merits of the technology itself. Therefore, to grow a user base, 
    Rakudo needs to deliver not only the benefits of the Perl 6 language itself, but also 
    a stable and performant implementation of it. It's a wider issue than Rakudo, but we 
    also need lots of good modules and, perhaps, some kind of killer app. Those kinds of 
    things will come from the community at large rather than just the core Rakudo team, 
    however they matter significantly to Rakudo's own success.
    How can people help you?
    There's so much that needs doing in the Perl 6 world today! Generally, I just advise 
    interested people to take a look around, spot something interesting to help with or 
    something that's missing that they would like to work on, and dig in! Perl 6 is very 
    much about -Ofun. For some of us, fun is compiler guts. For others, fun is web 
    frameworks. For others, fun is making awesome documentation. If you want to help, find 
    what's fun for you, do it well, and make your mark on the evolving Perl 6 community.

    ■_ メタクラスのなぞ

    Python metaclasses in depth - Jason in a Nutshell
    Python metaclasses in depth
    Metaclasses have a reputation for being among the blackest of Python's black magic. 
    As it turns out, they're actually pretty simple, but they require you to understand 
    some concepts. There are two ways to learn metaclasses in Python:
    メタクラスは Python にまつわる黒魔術の blackset のための reputation を持っています。
    Python におけるメタクラスを学ぶには二通りの方法があります:
       1. Skip the details and get straight to a useful implementation of a metaclass.
          詳細をスキップしてメタクラスの便利な実装を straightに理解する。
       2. Understand the core concepts behind metaclasses.
    Number 1 is useful, but will only get you so far. If you really want to understand 
    metaclasses, you need to take approach number 2.
    With that in mind, I'm going to start with the basics of how classes are constructed 
    in Python. Let's consider the following class:
    そういったことを念頭においてPython ではどのようにクラスが構築されるのかの基本からはじ
    class SomeClass(object):
         x = 1
         y = 2
    If you're ready to learn about metaclasses, the above statement shouldn't require much 
    thought to understand. But let's stop to think about it a bit anyway. In Python, 
    everything is an object. Therefore, classes are also objects. But if SomeClass is an 
    object, it must be an instance of some class. Let's find out what that class is:
    let's stop to think about it a bit anyway.
    Python ではすべてがオブジェクトです。当然、クラスもまたオブジェクトです。しかし、もし 
    SomeClass がオブジェクトであるのならそれは何らかのクラスのインスタンスでなければなりま
    せんクラスがいったいなんであるのかを突き止め (find out) ましょう:
    >>> type(SomeClass)
    <type 'type'>
    So apparently, it's an instance of type. We just saw the most common usage of type: to 
    query an object's type. But have you ever read the help on that function?
    してみるとどうやらこれは type のインスタンスです。あるオブジェクトの型を問い合わせる 
    (query) ために最も一般的な型の使用法だけを見ることにしましょうところであなたはこれまで
    >>> help(type)
    Help on class type in module __builtin__:
    __builtin__モジュールでの type クラスについてのヘルプです:
    class type(object)
     |  type(object) -> the object's type
     |  type(name, bases, dict) -> a new type
    So it turns out that type is not only a builtin function, it's also a class! How do we 
    instantiate an instance of type? You've already seen the most obvious way: using a 
    class statement. But did you know that you can create a class using type?
    さて、type が組み込みの関数であるだけでなくクラスでもあることがわかりました!
    わたしたちはどのようにすれば type のインスタンスを作り出せるのでしょうか?
    あなたはすでにclass 文を使うというもっとも明白な方法を見ています。
    でも type を使ってクラスを作れることをご存知でしたか?
    SomeClass = type('SomeClass', (object,), {'x' : 1, 'y' : 2})
    For all intents and purposes, the above statement is equivalent to the prior 
    definition of SomeClass. But this way is ugly and isn't used very commonly. That said, 
    we've demonstrated something: type isn't just any class. It's the class of classes. 
    It's a metaclass.
    すべての intents と purposses について、上の文は先にあった SomeClass の定義と同じです。
    しかしこの方法は ugly であり、かつ広く一般的につかわれているものではありません。
    type は単なる何かのクラスではありません。
    Let's go a step further though. How does the compiler generate the dictionary that's 
    the third argument to type? As it turns out, classes have something in common with 
    functions: they have local namespaces. You might have seen the locals function used 
    like this:
    ではさらに順を追っていってみましょう。コンパイラーはどのようにして type の第三引数であ
    る辞書を生成するのでしょうか? まず明らかに、クラスは関数と一緒に何かを持っています。
    その関数はローカルな名前空間を持っています。次のようなlocals() 関数を見たことがあるか
    def some_func():
        x = 1
        y = 2
        print locals()
    If you execute this, the output is this:
    >>> some_func()
    {'y': 2, 'x': 1}
    If classes have their own namespaces, then they must also be able to use the locals 
    function as well:
    クラス(の群)がここに固有の名前空間を持っていたならば、それらは同様に locals 関数が使え
    >>> class SomeClass(object):
    ...     x = 1
    ...     y = 2
    ...     print locals()
    {'y': 2, 'x': 1, '__module__': '__main__'}
    The only difference here is that the namespace is generated at import time and passed 
    into the type function.
    import されたときに生成され、type 関数に渡されているということです。
    So this is all interesting, but we haven't really seen anything terribly useful yet. 
    Let's go further. We've seen that type is the class of classes. But if type is a class, 
    then we must be able to subclass it. There are a number of reasons you might want to 
    do this. For instance, you may sometimes want to attach a property to a class rather 
    than to an instance. Let's do just that:
    So this is all interesting,
    but we haven't really seen anything terribly useful yet. 
    Let's go further.
    わたしたちは注目している type がクラスのクラス (class of classes) であることを見てきま
    した。しかしもし type が何らかのクラスであるのなら、そのサブクラス化が可能でなければな
    えば、インスタンスにではなくクラスにプロパティを attach したいと望むこともあるでしょう。
    class SomeMetaClass(type):
        def z(self):
            print 'In class property z'
            return self.x + self.y
    >>> SomeClass = SomeMetaClass('SomeClass', (object,), {'x' : 1, 'y' : 2})
    >>> SomeClass.z
    In class property z
    But we don't want to use this same ugly notation for creating SomeClass. Python 
    provides syntactic sugar for this. We can instead define SomeClass like this:
    しかしわたしたちは SomeClass を生成するためのものと同じこの醜い表記 (ugly notation) を
    使いたくはありません。Python はこれに対する構文糖 (syntactic sugar) を用意しています。
    わたしたちは SomeClass を次のように定義できます:
    class SomeClass(object):
        __metaclass__ = SomeMetaClass
        x = 1
        y = 2
    A more common use of metaclasses is to create a class constructor. Let's attach z to 
    the class directly rather than defining a property:
    ティを定義するのではなくz をアタッチしてみましょう:
    >>> class SomeMetaClass(type):
    ...         def __init__(self, name, bases, dict):
    ...             self.z = self.x + self.y
    >>> class SomeClass(object):
    ...         __metaclass__ = SomeMetaClass
    ...         x = 1
    ...         y = 2
    >>> SomeClass.z
    As we can see, we've defined a constructor for SomeClass. Now let's go a bit further. 
    What if we want to change the base class of SomeClass? That can be done, but we have 
    to use a __new__ method. I'm going to presume that you know a bit about __new__ 
    methods. If you don't, you might want to read up on them.
    Now let's go a bit further. 
    SomeClass のベースクラスを変更したいときには?
    そういった変更は可能ですが、__new__ メソッドを使わなければなりません、
    わたしはあなたが多少なりとも __new__メソッドについて知っていると仮定します。
    you might want to read up on them.
    >>> class SomeMetaClass(type):
    ...     def __new__(cls, name, bases, cls_dict):
    ...         new_cls = type.__new__(cls, name, (dict,), cls_dict)
    ...         return new_cls
    >>> class SomeClass(object):
    ...     __metaclass__ = SomeMetaClass
    ...     x = 1
    ...     y = 2
    >>> x = SomeClass()
    >>> x['foo'] = 'bar'
    >>> x
    {'foo': 'bar'}
    That should hopefully give you an idea of what metaclasses are and how to use them. If 
    you're even more lost than you were before, don't worry. This is just one of those 
    things that requires an “aha!” moment. You might also want to check out Michael 
    Foord's great Meta-classes Made Easy for a different perspective.
    If you're even more lost than you were before,
    それはただ単に  “aha!” moment を要求する just one of those things
    You might also want to check out Michael Foord's
    great Meta-classes Made Easy for a different perspective.

    ■_ 本日の巡回から


    そうそう。ふと思いついたことで根拠も裏付ける資料もないんだけど、 FORTRAN の暗黙の型宣言について。

    整数型は I から N までの文字で始まるものですが、 アルファベット26のうちそこに当てはまるのは 6個。 この6という数字なんですが、まず、FOTRAN I では配列は三次元までしか許されません。 それはなぜかというと、実装に使われた IBM 704 のハードでは インデックスレジスタが三つしかなかったためらしいということなんですね (これも一次資料では未確認です)。

    で、代入の左右それぞれに三つ添え字を使ったとすると、×2 で6. ということなんじゃあなかろうかと。 FORTRAN I には宣言文がありませんから、変数の型(といっても整数型か実数型だけ)は 暗黙の型宣言によるよりしかたありません。で、全体のうちどれだけ整数にするのか 実数にするのかを考えると、整数の主な使い道は配列の添え字やループの制御であり (DOループの制御変数に実数型がゆるされてたりしたんですが)、 あまり多くを整数型に振り分けるのをためらって、 この6という数字が出てきたのではないのかなあと。

    じゃあ始まりが I なのは? というのはまだ謎なわけなんですが(多分ループの制御変数の名前についての 慣習からきたのだろうとは踏んでいます)。



    LL Tiger の残りとか、国会図書館のこととかまとめている余裕がなっしんぐ。

    サービス・プロバイダーとは - はてなキーワード


    ■_ \K

    5.10 から使えるので、そこそこ時間が経っているのだけどあまり知られてないのかな。 というかうまい活用例があんまり思い浮かばない。 この回答みたいなパターンになるのだろうけど。

    正規表現 Part7 [chaika]
    377 デフォルトの名無しさん [sage] 2010/08/10(火) 22:29:01 ID: Be:
    378 デフォルトの名無しさん [sage] 2010/08/10(火) 23:25:35 ID: Be:
        やって見りゃVariable length lookbehind not implementedになるのはすぐわかるだろ。
        この例だと.*は余計なので取り除いて /(?<=_number=)¥d*/ にすればいいと思うが。
    379 デフォルトの名無しさん [sage] 2010/08/11(水) 06:32:21 ID: Be:
    380 デフォルトの名無しさん [sage] 2010/08/11(水) 07:10:06 ID: Be:
    381 デフォルトの名無しさん [sage] 2010/08/11(水) 07:17:20 ID: Be:
    382 デフォルトの名無しさん [sage] 2010/08/11(水) 08:39:22 ID: Be:
        perl -e '"x_hoge_number=100"=~/x_.*_number=¥K¥d*/ and print $&%'
    383 デフォルトの名無しさん [sage] 2010/08/11(水) 13:52:06  ID: Be:
    384 デフォルトの名無しさん [sage] 2010/08/11(水) 20:18:38 ID: Be:

    ■_ あんこくめん

    餡子喰う men ではなく。

    いけね。もとのpdf どこに置いてあったんだっけこれ。 スライドから適当に抜き出しています。

    The Dark Side of C++
    Felix von Leitner
    CCC Berlin
    August 2007
    Most of the perceived benefits of C++, when viewed from a different
    vantage point, turn out to have or even be downsides.
    Central Complaints
    1・new bug classes
    2・hard to write
    3・hard to read
    Why I Learned C++
    (なぜ C++ を学んだのか)
    ・OOP with Inline Member Functions
      インラインメンバー関数を使った OOPができたから
    ・(Operator) Overloading
    ・Templates (STL didn't exist yet)
      テンプレートが(ただし STLはまだなかった)
    C++ is hard to parse
    #C++ (のプログラム) はパーズするのが困難
    Not just for humans, too:
    template<class T> struct Loop { Loop<T*> operator->(); };
    Loop<int> i, j = i->hooray;
    This sends the compiler into an endless loop until swap exhaustion.
    C++ is hard to parse
    struct a{typedef int foo;};struct a1:a{};struct a2:a{};
    #define X(b,a) struct a##1:b##1,b##2{};struct a##2:b##1,b##2{};
    X(l,m)X(m,n) n1::foo main(){}
    In each iteration, the compiler must check whether the types of foo on
    both sides of the multiple inheritance match.
    g++ used to eat a gig of RAM and a couple CPU hours・icc still does.
    C++ is hard to parse
    ・string a("blah"); instantiates a string and assigns ”blah”, but
      string a(); declares a local function returning a string.
      string a("blah") は string のインスタンス、string a() は関数宣言。
    ・a &&& b evaluates a, and if it's true, it also evaluates b.
      Unless someone declared operator&&, then both are evaluated.
    ・(foo) + a*b; becomes +(foo,*(a,b)).
      Unless foo is a type, then it's *(typecast(a,foo),b).
    ・a, b means a is evaluated before b.
      Unless someone declared operator,, then it's not guaranteed.
    C++ is hard to write
    cin has a type conversion to void*
    So you can do while (cin) { ...
    Why void* and not bool?
    Because then cin << 3 would not be a compile time error.
    It would convert cin to bool, convert that to int and left-shift it by 3.
    cin は void* への型変換演算子を持っているが、bool はない。なぜか。
    C++ is hard to write
    ・Can't throw exceptions in destructors, shouldn't in constructors
    ・Initializers done in order of declaration of fields in class, not written order
    ・auto_ptr is useless
    ・Iterators don't know anything about the container, can't detect errors
    ・For a vector, at() does bounds checking, but operator[] doesn't
    ・Can't call virtual member functions from constructor or destructor
    The Dark Side of C++ 15
    Iterators and their Containers
    ・Iterators are like dumb pointers
    ・Don't know anything about the container
    ・Silent breakage if you do a.remove(b.begin())
    ・Iterator to removed element
    ・Iterator to stale element (resized vector, or balanced tree after rebalance)
    ・Iterator into destructed container
    C++ is hard to read
    baz = foo->bar(3);
    What does this code do? Looks easy enough, right?
    C++ is too powerful
    C++ は強力すぎる
    ・Boost.Lambda: for_each(a.begin(), a.end(), std::cout << _1 << ' ');
    ・C++ Expression Templates
    ・Vector a,b,v; v = a /vectorProduct/ b;
    ・Most people can't handle all that flexibility
    ・Code leaks resources when someone throws an exception
    ・Have to provide assignment operator, but fail if someone does a=a;
    ・Get hurt by stumbling blocks like auto_ptr
    Other nitpicks
    ・When disassembling, you can detect C++ code by the tons of do-nothing wrappers
    ・Linkers remove unreferenced code
        but virtual function tables do reference the virtual functions.
        So the linker includes all overwritten virtual functions from base classes.
    ・Can't tell what exceptions a library can throw
    Exception Safety
    char* read_first_n_bytes_from_file(const char* file,size_t n) {
      int handle=open(file,O_RDONLY);
      char* buf=new char[n];
      return buf;
    If new[] throws an exception, this leaks a file handle and deadlocks the next caller.
    delete vs delete[]
    void foo(int* x) {
      delete[] x;
    This will just call operator delete, which calls free().
    delete vs delete[]
    void bar(class foo* x) {
      delete[] x;
    This also calls the destructors.
    How does it know how many destructors to call?
    delete vs delete[]
    void bar(class foo* x) {                                testq %rdi, %rdi
        delete[] x;                                         je .L6
    }                                                       movq -8(%rdi), %rax
                                                            leaq (%rdi,%rax,4), %rbx
    int n=((int*)x)[-1];                                    cmpq %rbx, %rdi
    class foo* y=x[n-1];                                    je .L4
    while (y!=x) {                                     .L7:
        y->~foo();                                       subq $4, %rbx
        --y;                                                movq %rbx, %rdi
    }                                                       call _ZN3fooD1Ev
    delete x;                                               cmpq %rbx, %rbp
                                                            jne .L7
                                                            addq $8, %rsp
                                                            leaq -8(%rbp), %rdi
                                                            popq %rbx
                                                            popq %rbp
                                                            jmp _ZdaPv
    Local static initialization not thread-safe
    int bar() {                                        cmpb $0, _ZGVZ3barvE3bla
        static struct foo bla;                         je .L5
        return bla.member;                             movl _ZZ3barvE3bla, %eax
    }                                                  addl $12, %esp
                                                       [call constructor]
                                                       movb $1, _ZGVZ3barvE3bla
                                                       [handle exceptions]
                                                       movl _ZZ3barvE3bla, %eax
    gcc 4 calls a guard function in libstdc++ that actually acquires a (global, static) mutex.

    ■_ Perl 6

    遅い遅いといわれるのは、まったく使われずに無視されるより良いという 受け取られ方をしているようです。

    blog | Perlgeek.de :: Perl 6 Questions on Perlmonks
    Tue, 10 Aug 2010
    Perl 6 Questions on Perlmonks
    Permanent link
    Since the Rakudo Star release, there has been a noticeable increase in Perl 6 
    questions on perlmonks - a good sign, because it means people are using it.
    Rakudo Star がリリースされて以来、perlmonks に寄せられる Perl 6に関する
        * Array interpolation in Rakudo
        * Rakudo build problems
        * Perl6, latest Rakudo bug or error on my part? (parsing issue related to
          missing whitespace).
        * Perl6, modifying @*INC (another ws parsing issue)
        * Perl6's LWP::Simple -- seemingly an installation issue
        * Perl 6, defining a hash with interpolated string
    I've assembled this list by looking through the 100 newest nodes in Seekers of Perl 
    Wisdom, which makes it 6% of the questions asked, or on average 1 per day (used to be 
    around 1 per week).
    Most of the questions are related to environmental issues (building/installing stuff), 
    or beginner's questions related to syntax.
    It's good to see the questions flowing in, and I hope that we'll soon see more 
    questions where I can show off cool Perl 6 features in the answers :-).

    ■_ Perl6 First Impressions


    Perl6 First Impressions - Mad, Beautiful Ideas
    Perl6 First Impressions
    By Jeff Craig on August 10, 2010 8:00 AM 1 Comment No TrackBacks
    Perl6 looks pretty solid, from a language design standpoint. It cleans up a lot of the 
    cruft people have long complained about in Perl, like changing the glyph in front of a 
    symbol to change the way you're accessing that symbol, to support for (optional) 
    strong typing of variables, and so on. It's a well designed language, and 
    implementations, like Rakudo, are complete enough to be useful.
    I decided to play around with the classic Factorial problem to test some simple 
    implementations of the problem. First, I did a basic, naive implementation.
    sub fact($n) {
        return 1 if $n <= 1;
        return $n * fact($n - 1 );
    This is a simple solution, but as I said it's naive. It does a lot more work, since 
    if you try to get all the factorials from 1 to 100, it has to recalculate each one 
    individually, even though it's repeating a lot of work. But, Perl will memoize 
    my @factorialCache = 1, 1;
    sub fact($n) {
        @factorialCache[$n] = $n * fact($n - 1) unless @factorialCache[$n];
    This does precisely the same thing, except that it caches runs, so that if I've 
    already calculated the factorial of 5, when I go to do the factorial of 6, it's only 
    two function calls, instead of 6. This is memoization, and it's a cool functional 
    technique, basically creating a lookup table in real time, instead of pre-computing 
    all the values.
    このとき、配列要素にアクセスするときにも sigil に @ を使っていることに注意。
    Of course, the @factorialCache is available globally in this implementation, but I was 
    having trouble figuring out how to do recursion inside of a closure for creating a 
    generic memoizer that would use closure. I tried this:
    sub memoizer($function, @initialValues) {
        my @cache = @initialValues;
            return sub($n) {
            @cache[$n] = $function($n) unless @cache[$n];
    my $fact = memoizer( {
        return $^a * $fact($^a - 1);
    }, [1, 1]);
    This doesn't compile, however, as Perl tries to reference $fact in the anonymous code 
    block, but $fact hasn't been initialized yet. The $^a syntax is interesting, because 
    it's a ‘placeholder argument'. I could have assigned $a by either my ( $a ) = @_; or 
    my $a = @_[0];, but by using the caret, I'm telling Perl6 to pull those variables out 
    of @_, in the order that I declare my placeholders. It's a tiny bit dangerous, but for 
    small anonymous functions like this, it shouldn't be a problem.
    In Perl5, this required something called the Y-Combinator. In Perl6, there is 
    something to do with the &?BLOCK keyword, but I'm having trouble getting that to 
    Perl 5 ではこれを解決するのに Yコンビネーターのようなものが必要だったけど、
    Perl 6 では &?BLOCK という特殊変数(?)がある。しかしそれでも…
    That may be Rakudo, since other things in the Perl6 spec aren't complete yet, such as 
    using the state keyword when creating an iterator using gather-take syntax, which I 
    was a bit disappointed to find didn't seem to work in a way that allowed for elegant 
    memoization of this problem, but that may be me not fully understanding that feature 
    as well.
    It's rare these days I have cause to do much Perl. I've always been fond of the 
    language, and I hope Perl6, with it's cleaner and more powerful syntax, can help bring 
    more people back to the Perl community.

    ■_ 本日の巡回から

    一つ前へ 2010年8月(上旬)
    一つ後へ 2010年8月(下旬)


    Copyright (C) 2010 KIMURA Koichi (木村浩一)

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