ときどきの雑記帖 再起編

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

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

ホームへ

2012年03月10日

■_

月に一度のアレでした。 名古屋は来週の模様 tapl-nagoya - Front Page

で、今回は18章のあたりをやっていたのですが、「Open Recursion」のあたりで 結構盛り上がりました(というかわたしがわからんことを訊きまくっていたわけなんですが)。 オブジェクト指向プログラミングの特徴として以下のような5項目が挙げられていて (各項目の説明は割愛。知りたい人はTaPl参照)、

  1. Multiple representations
  2. Encapsulation
  3. Subtyping
  4. Inheritance.
  5. Open recursion.

わざわざ「open」とくっついている 「recursion」ってなんじゃらほい。と。 説明として

Another handy feature offered by most languages with objects and classes is the ability for one method body to invoke another method of the same object via a special variable called self or, in some languages, this. The special behavior of self is that it is late-bounded, allowing a method defined in one class to invoke another method that is defined later, in some subclass of the first.

とはあるのですが、それだけ読んでてもなにがなにやら。 「外に開かれている」というのがぴんとこないのですよねえ。

Open Recursion | Lambda the Ultimate

Open Recursion

I've been contemplating an embedded DSL. It strikes me how incredibly useful open recursion
would be for what I want to achieve, to the point that I might want to give the technique
some kind of explicit support and encouragement. Curious to see what had already been done,
a quick google search turned up Closed and Open Recursion by Ralf Hinze.

    Open recursion Another handy feature offered by most languages with objects and classes
    is the ability for one method body to invoke another method of the same object via a
    special variable called self or, in some langauges, this. The special behavior of self
    is that it is late-bound, allowing a method defined in one class to invoke another method
    that is defined later, in some subclass of the first. 

ところで、型理論で2005年頃にあった飛躍的な進歩ってなんざんしょ Dependent type - Wikipedia, the free encyclopedia

んで、open recursion 絡みの説明で出てきたクラス定義の数々。

  setCounterClass =
    λr:CounterRep.
      fix
        (λself: SetCounter.
          {get = λ_:Unit.  !(r.x),
           set = λi:Nat.   r.x:=i,
           inc = λ_:Unit. self.set (succ (self.get unit))});

 setCounterClass : CounterRep → SetCounter
 setCounterClass =
   λr:CounterRep.
      λr:SetCounter.
         {get = λ_:Unit. !(r.x),
          set = λi:Nat.  r.x:=i,
          inc = λ_:Unit. self.set (succ(self.get unit))}

 setCounterClass : CounterRep → SetCounter → SetCounter

↑には実は問題があって、それは↓のようにサブクラスを定義すると…

 instrCounterClass =
   λr:InstrCounterRep.
       λself: InstrCounter.
          let super = setCounterClass r self in
            {get = super.get,
             set = λi:Nat. (r.a:=succ(!(r.a)); super.set i),
             inc = super inc,
             accesses = λ_:Unit, !(r.a)};

 instrCounterClass : InstrCounterRep → InstrCounter → InstrCounter

  newInstrCounter =
    λ_:Unit. let r = {x=ref 1, a=ref 0} in
                 fix (instrCounterClass r);

  newInstrCounter : Unit → InstrCounter

この問題を解決するのにはいくつか方法があって(三つ挙げられていた)、 たとえば thunk を持ち込んでこう。


 setCounterClass =
   λr:CounterRep.
   λself: Unit→SetCounter.
      λ_:Unit.
         {get = λ_:Unit. !(r.x),
          set = λi:Nat.  r.x:=i,
          inc = λ_:Unit. (self unit).set(succ((self unit).get unit))};

  setCounterClass : CounterRep → (Unit→SetCounter) → Unit → SetCounter

買ったはいいけど積んだままになっている人は一度来てみるといいんじゃないかな?
Types and Programming Languages Advanced Topics in Types and Programming Languages
(Advanced…をどうするかは決まってないんだけどねw)

■_

The Mystery of the Duqu Framework - Securelist

The Mystery of the Duqu Framework - Securelist

The Mystery of the Duqu Framework

While analyzing the components of Duqu, we discovered an interesting anomaly in the main component that is responsible for its business logics, the Payload DLL. We would like to share our findings and ask for help identifying the code.

Code layout

At first glance, the Payload DLL looks like a regular Windows PE DLL file compiled with Microsoft Visual Studio 2008 (linker version 9.0). The entry point code is absolutely standard, and there is one function exported by ordinal number 1 that also looks like MSVC++. This function is called from the PNF DLL and it is actually the “main” function that implements all the logics of contacting C&C servers, receiving additional payload modules and executing them. The most interesting is how this logic was programmed and what tools were used.

The code section of the Payload DLL is common for a binary that was made from several pieces of code. It consists of “slices” of code that may have been initially compiled in separate object files before they were linked in a single DLL. Most of them can be found in any C++ program, like the Standard Template Library (STL) functions, run-time library functions and user-written code, except the biggest slice that contains most of C&C interaction code.

Layout of the code section of the Payload DLL file

This slice is different from others, because it was not compiled from C++ sources. It contains no references to any standard or user-written C++ functions, but is definitely object-oriented. We call it the Duqu Framework.

The Framework

Features

The code that implements the Duqu Framework has several distinctive properties:

    Everything is wrapped into objects
    Function table is placed directly into the class instance and can be modified after construction
    There is no distinction between utility classes (linked lists, hashes) and user-written code
    Objects communicate using method calls, deferred execution queues and event-driven callbacks
    There are no references to run-time library functions, native Windows API is used instead

Objects

All objects are instances of some class, we identified 60 classes. Each object is constructed with a “constructor” function that allocates memory, fills in the function table and initializes members.


Constructor function for the linked list class.

The layout of each object depends on its class. Some classes appear to have binary compatible function tables but there is no indication that they have any common parent classes (like in other OO languages). Furthermore, the location of the function table is not fixed: some classes have it at offset 0 of the instance, but some does not.


Layout of the linked list object. First 10 fields are pointers to member functions.

Objects are destroyed by corresponding “destructor” functions. These functions usually destroy all objects referenced by member fields and free any memory used.

Member functions can be referenced by the object’s function table (like “virtual” functions in C++) or they can be called directly. In most object-oriented languages, member functions receive the “this” parameter that references the instance of the object, and there is a calling convention that defines the location of the parameter – either in a register, or in stack. This is not the case for the Duqu Framework classes – they can receive “this” parameter in any register or in stack.


Member function of the linked list, receives “this” parameter on stack

Event driven framework

The layout and implementation of objects in the Duqu Framework is definitely not native to C++ that was used to program the rest of the Trojan. There is an even more interesting feature of the framework that is used extensively throughout the whole code: it is event driven.

There are special objects that implement the event-driven model:

    Event objects, based on native Windows API handles
    Thread context objects that hold lists of events and deferred execution queues
    Callback objects that are linked to events
    Event monitors, created by each thread context for monitoring events and executing callback objects
    Thread context storage manages the list of active threads and provides access to per-thread context objects

This event-driven model resembles Objective C and its message passing features, but the code does not have any direct references to the language, neither does it look like compiled with known Objective C compilers.


Event-driven model of the Duqu Framework

Every thread context object can start a “main loop” that looks for and processes new items in the lists. Most of the Duqu code follow the same principle: create an object, bind several callbacks to internal or external events and return. Callback handlers are then executed by the event monitor object that is created within each thread context.

Here is an example pseudocode for a socket object:

SocketObjectConstructor {
    NativeSocket = socket();
    SocketEvent = new MonitoredEvent(NativeSocket);
    SocketObjectCallback = new ObjectCallback(this, SocketEvent, OnCallbackFunc);
    connect(NativeSocket, ...);
}
OnCallbackFunc {
    switch(GetType(Event)) {
    case Connected: ...
    case ReadData: ...
...}
}

Conclusions

    The Duqu Framework appears to have been written in an unknown programming language.
    Unlike the rest of the Duqu body, it's not C++ and it's not compiled with Microsoft's Visual C++ 2008.
    The highly event driven architecture points to code which was designed to be used in pretty much any kind of conditions, including asynchronous commutations.
    Given the size of the Duqu project, it is possible that another team was responsible for the framework than the team which created the drivers and wrote the system infection and exploits.
    The mysterious programming language is definitively NOT C++, Objective C, Java, Python, Ada, Lua and many other languages we have checked.
    Compared to Stuxnet (entirely written in MSVC++), this is one of the defining particularities of the Duqu framework.

The Duqu Framework: What was that?

After having performed countless hours of analysis, we are 100% confident that the Duqu Framework was not programmed with Visual C++. It is possible that its authors used an in-house framework to generate intermediary C code, or they used another completely different programming language.

We would like to make an appeal to the programming community and ask anyone who recognizes the framework, toolkit or the programming language that can generate similar code constructions, to contact us or drop us a comment in this blogpost. We are confident that with your help we can solve this deep mystery in the Duqu story.


© 1997-2012 Kaspersky Lab ZAO. All Rights Reserved.

■_ Camel Book

Perlについての質問箱 51箱目

68 デフォルトの名無しさん [] 2012/03/08(木) 15:42:45.77 ID: Be:
    Programming Perlの新しいのが出るらしいけどお前たちは買いますか?
    http://www.amazon.co.jp/dp/0596004923/ 

69 デフォルトの名無しさん [sage] 2012/03/08(木) 15:45:28.75 ID: Be:
    日本版じゃねーじゃん 

96 デフォルトの名無しさん [sage] 2012/03/10(土) 01:47:59.87 ID: Be:
    >>68
    今日届いた。らくだ本は青くなってからだじゃれが減ってつまんないよ。
    版が上がってますますそう感じる。それともおいらのセンスがないのかな。 

97 デフォルトの名無しさん [sage] 2012/03/10(土) 12:50:05.11 ID: Be:
    日本語の第四版持ってるけどどんな所が改訂されたんだろう 

98 デフォルトの名無しさん [sage] 2012/03/10(土) 12:51:35.46 ID: Be:
    >>97
    ラクダの右足踏み込みが2ドット深くなってます。 

99 デフォルトの名無しさん [sage] 2012/03/10(土) 13:22:01.47 ID: Be:
    翻訳されたのが出るのは何年後? 

100 デフォルトの名無しさん [sage] 2012/03/10(土) 15:35:25.50 ID: Be:
    2年後でしょうね。
    その頃はPerl5.18なので、脚注で補われるかと。 

97 はなにを言ってるんだろう…

■_ Battle of the 80's

むかーーーしの広告をタネに盛り上がり。 Battle of the 80's - advertisement for the Z80 from May 1976 : programming

Battle of the 80's - advertisement for the Z80 from May 1976 : programming

Fun Fact: TI - 83 and 84 calculators are Z80 powered.


Also the '85 and '86

I wrote a game in Z-80 assembly for my TI-85 as a teenager and still feel slightly 
badass about it. It's probably the peak achievement of my life.


And, more importantly, the Sega Master System.


And that is why I learned Z80 before I learned C++.



For example, the 8080A didn't have relative branches at all (8085 did, I think?), so yeah,
that was something worth crowing about. The single (2-byte) instruction block move (LDIR)
was nice too, especially when you were usually byte-counting and cycle-counting. (Why do I
remember this? First paying job was on an IMSAI with a Z80 upgrade, though the TRS-80 at
home probably had more to do with it :-)

    8085 did, I think?

Nope. It was an enhancement of the 8080 that was easier to build systems with (didn't need
so many support chips), but there was no relative addressing.

LDIR - Load Increase and Repeat - the best opcode for all kind of scroll/game loops!

I used to own Rodnay Zaks' book, and program crappy games on my ZX spectrum using the 
'champ' assembler-editor!

Good times!


The real battle was between the z80 and the 6502.


Programmed heavily in both. The 6502 turned out to be overall better in terms of performance
- but programs were waaaay longer (the opcodes were less powerful, but executed way faster).


I did the 6502 for fun (C64) and the z80 for work (Control Data Corp. Micro-PLATO).

My impression was that at the low end the 1mhz 6502 was much better than the 2.5mhz z80,
but at the high end the 8mhz z80 had an edge over the 2mhz 6502.

Of course the z80 is still in production and running at over 20mhz, so in the long run 
it won.

あまり使ったことがないせいか 6502 ってそれほど好きではなかったり(嫌いでもないけど)。 好きな人はとことん好きって印象がありますよね。 しかしえらい値段がついてるなこれ

Apple2 1976‐1986
Apple2 1976‐1986

■_ PoweShell 3

もうちょっとこうがっつりいじりたいところではあるんだけど > PowerShell

InfoQ: Preview PowerShell 3 in the new Windows Management Framework 3 Beta

PowerShell 3 uses the Dynamic Language Runtime, which should provide substantial performance
improvements over PowerShell 2. The parser has been rewritten, and the API is now public.
Adam Driscoll writes about these changes:

PowerShell 3 は Dynamic Language Runtime を使っています。これは PowerShell 2 と
比較して大幅に性能が向上しています。そのパーザーは書き直しが行われ、API は public な
ものとなりました。Adam Dirscoll は変更点についてこう書いています

    The Compiler class is an ICustomAstVisitor. This means that the compiler tells the AST
    how it should be traversed. After some perusing around the members within this class I
    ran into the Compile method. The method accepts an AST and outputs an Expression. This
    means that the compiler visits each node into the AST and compiles it into a LINQ
    expression tree. Pretty wicked stuff! This expression can then be compiled and invoked.
    ... They are then stored as a DynamicMethod within the current process. Since it is
    compiled it won't need to be reinterpreted in the future.

なんで PowerShell やろうかってーと、書くに書けない事情がそこに…げふんげふん。

■_

2012年03月09日

■_

そういや DDD も積んだままだ。

■_

くだすれPython(超初心者用) その12

833 デフォルトの名無しさん [] 2012/03/08(木) 20:30:35.18 ID: Be:
    あるリストから、条件にマッチする最初の要素を取り出すのって、Pythonではどうかきますか。
    Rubyなら list.find {|x| x == foobar } と書くやつです。
    [ x for x in list if x == foobar ][0] かなとおもったけど、マッチしない時に例外が。 

834 デフォルトの名無しさん [sage] 2012/03/08(木) 21:16:09.35 ID: Be:
    ([ x for x in list if x == foobar ] + [None])[0] 

835 デフォルトの名無しさん [sage] 2012/03/08(木) 21:18:47.75 ID: Be:
    try ... exceptで振り分けて処理するんじゃないかな
    空リストだったらIndexErrorが上がってくる 

836 デフォルトの名無しさん [sage] 2012/03/08(木) 21:20:58.82 ID: Be:
    try except書くくらいならwhile break書いたほうが良くね 

837 デフォルトの名無しさん [sage] 2012/03/08(木) 21:21:43.51 ID: Be:
    それはないか 

838 デフォルトの名無しさん [sage] 2012/03/08(木) 21:53:44.53 ID: Be:
    >>834-836
    いい方法なさそうですね。
    for x in list:
     if x == foobar:
      break
    else:
     x = None
    いけてねー!
    もっといい方法を求む! 

839 デフォルトの名無しさん [sage] 2012/03/08(木) 22:03:15.99 ID: Be:
    例外起きたらそこでこかしたままでええんちゃうん?
    条件に合わないもん突っ込んどった方が悪いんちゃうん? 

840 デフォルトの名無しさん [sage] 2012/03/08(木) 22:11:47.66 ID: Be:
    要素が整数や文字列で、リストに同値が含まれているか調べるだけなら
    >>> 3 in [1,2,3]
    True
    >>> 4 in [1,2,3]
    False 

841 デフォルトの名無しさん [sage] 2012/03/08(木) 22:13:24.09 ID: Be:
    >>838
    834で何が不満なの? 

842 デフォルトの名無しさん [sage] 2012/03/08(木) 23:15:04.37 ID: Be:
    next((x for x in list if x == foobar), None) 

843 デフォルトの名無しさん [sage] 2012/03/08(木) 23:20:32.24 ID: Be:
    そんな関数があったのか 

844 デフォルトの名無しさん [sage] 2012/03/09(金) 00:43:48.27 ID: Be:
    わかりやすくって怒られるぞ 

845 デフォルトの名無しさん [sage] 2012/03/09(金) 06:53:30.64 ID: Be:
    素直に例外出すべき事例だろ 

846 デフォルトの名無しさん [sage] 2012/03/09(金) 07:12:53.72 ID: Be:
    forでぶん回してbreakで抜ける。これで勝つる
    forにelseをつけるのはインデントミスくさくていけてない 

なぞめいている>842

■_ A Matlab programmer's take on Julia

Matlab ユーザーが Julia を使ってみた

A Matlab programmer's take on Julia

2pif/ op/ A Matlab programmer's take on Julia
A Matlab programmer's take on Julia
M. Bazdresch

[I am running Julia Version 0.0.0-prerelease, Commit 6f25d4d84a (2012-03-01 07:50:31)]

Julia is a new language for numerical computing. It is fast (comparable to C), its syntax is
easy to pick up if you already know Matlab, supports parallelism and distributed computing,
has a neat and powerful typing system, can call C and Fortran code, and includes a pretty
web interface. It also has excellent online documentation. Crucially, and contrary to SciPy,
it indexes from 1 instead of 0.

For a Matlab programmer, it sounds like a dream come true, right? (I mean Matlab the 
language, not the commercial software; I use Octave exclusively). The Matlab language 
is slow, it is crufty, and has many idiosyncracies. A few examples:

Matlab プログラマーにとって、それは夢がかなったかのように聞こえます。違いますか
(わたしは Matlab は commercial software ではなく言語であるとみなしています。
exclusively に Octave を使っています)?
Matlab 言語は遅く、


    A line of code not ending in a semicolon will print its result to stdout.
    セミコロンで終わっていないコードの行はその結果を標準出力に出力する

    One function per .m file, both with the same name. The file may contain other functions
    but they are private to the function whose name corresponds to the file name.

    ひとつの関数は同じ名前のファイルを持った .m ファイルに置ける。
    そのファイルにほかの関数を含むことも可能だが、それらはファイル名に対応した
    名前を持つ関数に対して private なものになる

    No namespaces.

    名前空間がない

    You can do things such as

    sin=3;

    which shadows the sin function; doing clear sin will clear the variable and restore the function.
    のようなことができ、これは sin 関数を隠してしまう。
    clear sin を行うとこの変数を clear して関数を復帰する

    Many functions do very different things depending on how they are called and even how
    many output arguments are specified.

    多くの関数で、それがどのように呼ばれたかやいくつの出力引数が指定されたかによって
    非常に違ったことを行う

And the list goes on and on.
リストはまだ続きます

I strongly disagree, however, with the opinion, common among some circles, that Matlab 
is to be dismissed just because it is crufty or "not well designed". It is 
actually a very productive language that is very well suited to numerical computing 
and algorithm exploration. Cruftiness and slowness are the price we pay for its 
convenience and flexibility.

しかしながらわたしは、一部のサークルにおいて一般的な、
Matlab が

However, Julia's allure is strong, so strong that I have spent some hours exploring it, 
reading the manual, and perusing their GitHub repository. My conclusion is that I will not
switch to it in the short term, but I will keep an eye on it and periodically re-evaluate it.

一方で Julia の allure は強力です。とても強力なのでわたしは数時間かけてマニュアルを読み、
GitHub のリポジトリを perusing してしまったのです。
わたしの結論は、短期間で移行することはないけれども注目し続けて
perdiodicallyに再評価するだろうというものです。

I believe some of the concerns I have about Julia will be solved eventually. Some relate to
missing infrastructure. Others are small things that would make me less productive if I
switched to Julia today, compared to Octave, regardless of its strengths in speed,
parallelism, etc. Some things that come to mind are:

わたしは Juila が自分が抱えている関心事の一部を解決してくれるだろうと確信していますが、
一部はインフラが欠如していることに関連しています。
そのほかのものは今わたしが Julia に移行してもわたしを less productive してしまう
small things で、Octave と比較すると速度における優位性とは無関係に parallelism などです。
思い出せる範囲では


    No plotting, except in the web REPL, and only very simple (if pretty) 2D plots supported.

    web REPL 以外には plotting がなく、しかも非常に単純な 2D プロットしかサポートしていません

    No debugging facilities. No need for fancy IDE-style setting of breakpoints; Octave-style
    keyboard and db* functions would be good enough.

    debugging facillities がない。
    fancy な IDEスタイルのブレークポイントの設定は必要なくて、
    Octave スタイルの keyboard and db* functions があれば十分です

    No test suite.

    test suite がない

    No code autoloading. When exploring an algorithm or ironing out bugs, I usually have
    an Octave session in a terminal and my code in a gvim window. I change something in
    the code, alt-tab to the terminal and call my code. Octave will figure out by itself
    that the file containing the code has changed from the last time it was called, so it
    will reload it automatically. I can be sure Octave is always running the latest version
    of my code.

    In Julia, no autoloading is done. This means that I have to issue load("mycode.jl")
    before running my modified code. This is a minor but very real nuisance.

    No package management or global configuration. Julia will read a custom.jl file in the
    directory it's run from, if present, but there seems to be no way to do this globally.
    I can invoke Octave from anywhere in my system, and I will have access to all my packages
    without further action. Readline, the prompt, etcetera will all be set up the way I want.

    Sandboxing and security in the web REPL. How will I be able to read and write data files,
    while preserving filesystem privacy and security? I don't have the answer, and nothing
    about this is mentioned in the manual. Julia has the ability to run any function on the
    system's libc, which in principle means it will be able to wipe my home directory or
    upload my files to the cloud.

    The way vectors are handled is, frankly, weird. Let's build a column vector:

    vector の取り扱いは、率直に言っておかしなものです。
    ここで column vector を構築してみましょう

    julia> x = [1,2,3]
    [1, 2, 3]

    Note that, even though it's printed "horizontally", x is actually a column
    vector and it has only one dimension.

    "horizontally" に出力されているにもかかわらず、x は実際には column vector であり
    ひとつの次元しか持っていないことに注意してください

    julia> size(x)
    (3,)
    julia> ndims(x)
    1

    Now let's build a row vector:

    julia> y = [1 2 3]
    1x3 Int64 Array:
     1  2  3

    Note that, for some reason, Julia now prints the type of y along with its value. y is a
    row vector and, contrary to x, it is two-dimensional.

    何らかの理由で、今度は値に結びついている y の型を出力していることに注意してください。
    y は row vector であり、x とは違って二次元です。

    julia> size(y)
    (1,3)
    julia> ndims(y)
    2

    Under multiplication, x does indeed behave like a column vector:

    julia> y*x
    [14]

    Curiously, if we transpose y, we can build a two-dimensional column vector:

    julia> yt = permute(y,[2,1])
    3x1 Int64 Array:
     1
     2
     3
    julia> ndims(yt)
    2

    x and y may be multiplied, as shown above, but yt and x cannot be added, even though
    both are column vectors, since they have different number of dimensions:

    julia> x+yt
    argument dimensions must match

    The purpose of this way of handling vectors escape me, and I fail to see how it will
    make numerical programming easier or more powerful. Maybe a few years of Matlab
    programming will do this to you, but I find Matlab's conventions much more natural and 
    unobtrusive.
略
As a conclusion, I trust the authors will stay true to their vision and turn Julia into a
language that preserves most of Matlab's convenience and at the same time meets all of
their promises. It'd be a dream come true for those of us who spend a good deal of time
doing numerical computation. This post may sound too negative, but I complain because I
care. For the time being, alas, it's back to Octave for me.

■_

2012年03月08日

■_

不調

■_ Student Questions about Scala, Part 2

Student Questions about Scala, Part 2 - Java Code Geeks Part 2 から。


Student Questions about Scala, Part 2 - Java Code Geeks

Tuesday, 6 March 2012 Student Questions about Scala, Part 2

Preface

This is the second post answering questions from students in my course on Applied Text
Analysis. You can see the first one here. This post generally covers higher level questions,
starting off with one basic question that didn't make it into the first post.

Basic Question

Q. When I was working with Maps for the homework and tried to turn a List[List[Int]] into a
map, I often got the error message that Scala “cannot prove that Int<:<(T,U)”. What
does that mean?

宿題で List[List[Int]] を map に変換しようとしたときに、
“cannot prove that Int<:<(T,U)” という
Scala のエラーメッセージによく遭遇しました。
これはどういうことなのでしょうか?

A. So, you were trying to do the following.
   それはあなたが次のようなことをしようとしたからです

	scala> val foo = List(List(1,2),List(3,4))
	foo: List[List[Int]] = List(List(1, 2), List(3, 4))
	 
	scala> foo.toMap
	<console>:9: error: Cannot prove that List[Int] <:< (T, U).
	foo.toMap
	^

This happens because you are trying to do the following at the level of a single two-element
list, which can be more easily seen in the following.

これは二要素のリストひとつのレベルに対して行おうとしているのでこうなります。
次のようにするとよりわかりやすいでしょう

	scala> List(1,2).toMap
	<console>:8: error: Cannot prove that Int <:< (T, U).
	List(1,2).toMap
	^

So, you need to convert each two-element list to a tuple, and then you can call toMap 
on the list of tuples.

ですから二要素のリストはそれぞれタプルに変換する必要があり、
変換後のタプルのリストに対して toMap が呼びだせます。

	scala> foo.map{case List(a,b)=>(a,b)}.toMap
	<console>:9: warning: match is not exhaustive!
	missing combination            Nil
	 
	foo.map{case List(a,b)=>(a,b)}.toMap
	^
	res3: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4)

You can avoid the warning messages by flatMapping (which is safer anyway).

flatMapping によって警告メッセージを抑制できます

	scala> foo.flatMap{case List(a,b)=>Some(a,b); case _ => None}.toMap
	res4: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4)

If you need to do this sort of thing a lot, you could use implicits to make the conversion
from two-element Lists into Tuples, as discussed in the previous post about student questions.

こういったことを行う必要が多くあるのなら、前回の投稿にあった議論のように
二要素の List から Tuple  への変換を implicit なものにできます。

(略)

High level questions

Q. Since Scala runs over JVM, can we conclude that anything that was written in Scala, 
can be written in Java? (with loss of performance and may be with lengthly code).

Scala は JVM上で動いているので、Scala で書かれたものだけですべてを Java で書くことはできますか?

A. For any two sufficiently expressive languages X and Y, one can write anything in X 
using Y and vice versa. So, yes. However, in terms of the ease of doing this, it is 
very easy to translate Java code to Scala, since the latter supports mutable, 
imperative programming of the kind usually done in Java. If you have Scala code that 
is functional in nature, it will be much harder to translate easily to Java (though it 
can of course be done).

Efficiency is a different question. Sometimes the functional style can be less efficient
(especially if you are limiting yourself to a single machine), so at times it can be
advantageous to use while loops and the like. However, for most cases, efficiency of
programmer time matters more than efficiency of running time, so quickly putting together
a solution using functional means and then optimizing it later — even at the “cost” of
being less functional — is, in my mind, the right way to go. Josh Suereth has a nice blog
post about this, Macro vs Micro Optimization, highlighting his experiences at Google.

Compared to Scala, the amount of code written will almost always be longer in Java, due
both to the large amount of boilerplate code and to the higher-level nature of functional
programming. I find that Scala programs (written in idiomatic, functional style) converted
from Java are generally 1/4th to 1/3rd the number of characters of their Java counterparts.
Going from Python to Scala also tends to produce less lengthy code, perhaps 3/4ths to 5/6ths
or so in my experience. (Though this depends a great deal on what kind of Scala style you
are using, functional or imperative or a mix).

(略)

Q. General question/comment: Scala lies in the region between object-oriented and functional
programming language. My question is — Why? Is it because it makes coding a lot simpler and
reduces the number of lines? In that case, I guess python achieves this goal reasonably well,
and it has a rich library for processing strings. I am able to appreciate certain things,
and ease of getting things done in Scala, but I am not exactly sure why this was even
introduced, that too in a somewhat non-standard way (such a mixture of OOP and functional
programming paradigm is the first that I have 
heard of).

I'll defer to Odersky, the creator of Scala. This is from his blog post “Why Scala?“:

Scala took a risk in that, before it came out, the object-oriented and functional 
approaches to programming were largely disjoint; even today the two communities are 
still sometimes antagonistic to each other. But what the team and I have learned in 
our daily programming practice since then has fully confirmed our initial hopes. 
Objects and functions play extremely well together; they enable new, expressive 
programming styles which lend themselves to high-level domain modeling and and 
embedded domain-specific languages. Whether it's log-analysis at NASA, contract 
modelling at EDF, or risk analysis at many of the largest financial institutions, 
Scala-based DSLs seem to spring up everywhere these days.

Here are some other interesting reads that touch on these questions:

    Twitter on Scala
    InfoQ question: Why Scala?
    Bruce Eckel: Scala: The Static Language that Feels Dynamic (viewpoint from a Pythonista)

■_ become

reddit にしても Hacker Newsにしても ちょっと前の記事で盛り上がったりすることがわりとあります。 んでこれも200年のもの。

Room 101: The 
Miracle of become:


Room 101

A place to be (re)educated in Newspeak Thursday, July 30, 2009 The Miracle of become:

One of Smalltalk's most unique and powerful features is also one of the least known 
outside the Smalltalk community. It's a little method called become: .

Smalltalk の、最も unique かつ強力な機能の一つはまた、Smalltalk コミュニティの外ではあ
まり知られていない機能の一つでもあります。それは、become: と呼ばれている小さなメソッド
です。

What become: does is swap the identities of its receiver and its argument. That is, 
after

become: が行うことはそのレシーバーと引数の identities を交換です。つまり、

  a become: b

all references to the object denoted by a before the call point refer to the object 
that was denoted by b, and vice versa.

を実行すると、呼び出し前に a によって denote されていたオブジェクトに対するすべての参
照が b によって denote されていたオブジェクトを参照するようになります。またその逆に、b 
が denote していたオブジェクトに対するすべての参照は a によってdenote されていたオブジ
ェクトを参照するようになります。

(略)

Smalltalk become でぐぐったらある意味予想通りの結果が

■_

2012年03月07日

■_

歴史群像

■_

なぜ Objective-C は難しいのか

Why Objective-C is Hard » 
Ash Furrow

Why Objective-C is Hard

As an active member of "The Internet" and vocal Objective-C coder, I get a 
lot of questions surrounding the language. They're often framed around thinking about 
learning the language or trying to write an app, but they also usually involve a 
phrase like "Objective-C looks really hard" or "what are all those 
minus signs about?" Both of these are pretty good questions, and I'd like to 
address why someone might be more hesitant to jump into iOS or OS X development 
compared to, say, Ruby or Java.

わたしは Objective-C に関する質問を良く受けます。

“Objecive-C は本当に難しい”だとか“what are all those minus signs about?”といった感
じのことをいいます。これらはどちらもとてもよい質問で、


Syntax
構文


Let's talk about what a programming language is. A programming language is the 
human-readable code that expresses how a program behaves. A language consists of a 
syntax (rules for valid expressions and statements) and semantics (rules for how to 
organize those expressions and statements in meaningful ways to accomplish some task).

プログラミング言語とはなんなのかということについて話しましょう。プログラミング言語とは
あるプログラムの振る舞いを表現している人間が読めるコード (human-readable code) です。
言語は(正しい式と文の規則である)構文と、(式や文がどのように構成されるかの規則である) 
semantics から成り立っています。


Most (common) programming languages out there are based on the C-style syntax of method
invocation and the dot-syntax of accessing members of classes (well, structs in C).
They'll usually implement their own brand of class definition (Java differs a bit from C#
or C++), but the nuts and bolts of the language itself is the same. When approaching a new
language, seeing similarities in the syntax makes people feel more comfortable, and most
people know the C syntax.

大部分の (一般的な) プログラミング言語は、
メソッド呼び出しの構文やクラスのメンバーに対するアクセスでのドット構文
で C の構文を元にしています。
そういった言語はまた、通常は独自のクラス定義を実装するものなのですが
(Java は C# やC++ とは多少の相違があります)、言語それ自身の nuts と bolts は
同じものなのです。
新しい言語にアプローチするとき、構文の相似は人をより comfortable にさせますし、
最も知られているのはC の構文なのです。


Objective-C is a very different language with regards to its syntax. It's so different, 
even, that most people don't look at it long enough to realize that the semantics of the
language are almost identical to C++, Java, or others.

Objective-C は非常に変わった言語です。とても変わっているので、構文に関しては
ほとんどの人がこの言語が C++ や Java のようなものとほぼ同じ semantics であるとは
認識しません。

Even other "weird" languages like Python or Ruby are accessible because they at least use
the dot-syntax for method invocation and member access in classes. Lack of curly braces
doesn't bother people for long because they were probably indenting their code anyway.

Python や Ruby のようなほかの "weird" な言語でさえ、メソッドの呼び出しや
クラスのメンバーに対するアクセスにはドット構文を使っているので accessible なのです。
カーリーブレースの欠如はユーザーを飽き飽きさせるものではありません。
なぜなら、彼らは自分のコードをインデントしているでしょうから。

This is usually how introducing someone to Objective-C goes: I compare it with another 
OOP language.

(略)


で、画像で比較してるんですが Objective-C だと引数が増えるにつれて 記述が長ったらしくなると

  引数がない場合
  [object performAction];
  object.performAction();

  引数がひとつの場合
  [object performAction:firstParameter];
  object.performAction(firstParameter);

  引数が二つの場合
  [object performAction:firstParameter withTwoParameters:secondParameter];
  object.performAction(firstParameterm secondParameter);

のように比較してます。

■_

で、Hacker Newsでの反応から

Why Objective-C is Hard | Hacker News

People fret over language syntax too much. In most sane languages including Objective-C you
simply forget about the syntax after a few months. What's much more important is the
conceptual complexity: the number of language features and the way they fit together. A
second important thing is the standard library. Objective-C is a pleasant language by both
these metrics, since there are just a few language constructs above the C level, they fit
together well without creating dark corners, and Cocoa is a very mature and well thought-out
framework. The iOS Objective-C ecosystem does take some time to master, but so does every
modern SDK, since the libraries are always huge. Programming is hard and if somebody is
scared by minus signs in front of method names, evil spirits will suck his soul out by the
time he gets to thread synchronization.

It's best to think of Obj-C method call syntax as a sentence, written in english, which
happens to also be computer code. If you name your methods and variables succinctly and
explicitly, the language is extremely readable and documents itself (assuming you know english).

Obj-C was the first language I learned after Python. I remember the 2nd month in, it went
from being difficult to read, to extremely easy.

Obj-C code can be written terribly, like this:

    NSString *someString = @"hello what's up?";
    NSMutableString *anotherString = [NSMutableString stringWithString:@"I have more to say, don't I?"];
    NSArray *stringArray = [NSArray arrayWithObjects:someString, anotherString, nil];
    NSUInteger stringArraySize = [stringArray count];

Messy Obj-C code! Human eyes like simplicity, like right angles, and columns. Same 
code, more readable:

    NSString        *someString     = @"hello what's up?";
    NSMutableString *anotherString  = [NSMutableString stringWithString:@"I have more to say, don't I?"];
    NSArray         *stringArray    = [NSArray arrayWithObjects:someString, anotherString, nil];
    NSUInteger      stringArraySize = [stringArray count];

Takes an extra few seconds of typing, but goes miles.

綺麗に整形すればいい。ってのはどうなんだろか。

■_

2012年03月06日

■_

The Art of Readable Code - ククログ(2012-03-05) 英語なので読む人はいないでしょうが紹介します。読みやすい英語で書かれているので、「読みやすいコードだけではなく英語の勉強にも興味がある」という人にはちょうどよいでしょう。ページ数も200ページにいかないぐらいとコンパクトにまとまっています。 とはいえ、やはり英語だとなかなか読む気にならないことでしょう。そんなあなたにうれしいお知らせがあります。7月あたりにあの角さんの訳で翻訳版が出版されるそうです。

翻訳版がでるまでに読み終わらねば(今のところ30%台)。

■_ Lisp

Lisp に入門したいんですが。というお悩み

New to lisp, doing Land of Lisp, I feel like it's going to fast and have issues understanding parts which the book does not explain, I feel like I wouldn't be able to remember or come up with most of what he writes, is this normal? : lisp

New to lisp, doing Land of Lisp, I feel like it's going to fast and have issues understanding
parts which the book does not explain, I feel like I wouldn't be able to remember or come up
with most of what he writes, is this normal? (self.lisp)

So I started a few days ago with Land of Lisp, I'm at chapter 8 now, it wen't rather smooth
up 'til now, the only time I've really been confused has been coding the game-repl, although
I've had to google some things along the way due to the author simply not explaining what
some functions do. But now I'm here and have issues understanding most of it. I feel the
explanations of the author are insufficient for me and that even when I do understand it I
feel like I'm not being taught how to come up with such things. Obviously Lisp being a
little more on the obscure side, meaning I can't find answers on google a lot of the time,
doesn't help. Is this normal? Is this just me? My thoughts were that perhaps I should read
another book about lisp first. Can anyone recommend me one that goes more into detail about
code written and why the code is written in that way?

A little background information about myself, I've been programming C for a very long 
time and code in Java professionally. Obviously I'm new to functional programming 
coming from imperative languages.

I've thought about trying Scheme or Haskell (as both are mentioned in the 
"personality test" at the beginning of the book), but given the amount of 
cool things I've heard about Lisp I wasn't keen on that.

TL;DR: Starting lisp (and functional programming) with Land of Lisp, can't understand 
lots of what the author's doing and why. Should I start with another book or perhaps 
even another similar language?

Edit: Thanks for all the help, I started going through Practical Common Lisp (as it 
was recommended by many) and so I've decided I'll finish that first. How to Design 
Programs also seems interesting and so I plan to read that too.

■_

本文が結構長いんですが一部を

eugenkiss | Thoughts on upcoming PLs

05.03.2012
Thoughts on upcoming PLs
in programming programming-languages haskell kotlin rust dart

I've been pretty busy the last couple of months and it is going to stay that way for the
next couple of months as well so that's why there wasn't hardly any new content on this
site1. Nonetheless, I wanted to write down some thoughts I lately had about the one or
other upcoming programming language.

Haskell's weaknesses

The purpose of this section is to give you some insight on why I'm looking forward to new
languages instead of being already content (with Haskell).

Apart from coding in Java for university projects and briefly checking out the one or other
language I've been toying around with Haskell since round about one year. Some of the
impressions I had on Haskell can be found in some of my previous posts e.g. “Experience
Report: A Mastermind Simulation in Lua, Java & Haskell“. I've had a lot of praise in
respect to some of Haskell's virtues but at the same time I acknowledged its warts. The more
I programmed and thought about the things I want to create the more precise my ideas of what
I want from a language became and the bigger the warts seemed to me.

略
I don't have the source for the following paraphrased quote but I've read it a couple 
of times in the Haskell mailing list:

    Haskell makes some easy things harder and some difficult things easier

このあといろいろ目新しい言語の名前を出しながら長い文章が続きます。 しかし、some easy things harder and some difficult things easier って。

■_

There is something really wrong with modern programmers. : programming Cogs Bad - William Edwards, Coder

■_ VB11

ずいぶんとまあ InfoQ: A look at Visual Basic 11

  Dim listFunction = Iterator Function()
                         Yield 5
                         Yield 15
                         Yield 25
                     End Function

  For Each x in listFunction()
      Console.Writeline(x)
  Next

かなり無理やり(構文を)詰め込みました感が

■_ 信頼度成長曲線

それなりに聞く言葉ではあるのですが

信頼度成長曲線 - Wikipedia

信頼度成長曲線(しんらいどせいちょうきょくせん 英:Software Reliability Growth Curve)とは、
横軸に日付、テスト時間、またはテストケース数、縦軸に累積バグ発見数をとったグラフ。S字の成長
曲線を描くことが多い。

プロジェクトの進捗状態の確認などに用いる。

決定論的モデルとして、最小二乗法でゴンペルツ曲線やロジスティック曲線に近似したり、確率モデル
として、非同次ポアソン過程モデルなどで表したりすることにより、現在の状況から今後の予想を立て、
テスト進捗管理、バグ収束率の予測、残バグ数の予測などに用いることもある。

収束を見る場合に、横軸に日付を使った場合、テストをしていないからバグが出ないのか、テストを
してもバグが出ないのかの区別がつかないという問題がある。

英:Software Reliability Growth Curve とあるんですけど、 この言葉でぐぐってもそのものずばりを解説しているページが見当たらないのは なぜなんでしょうか? Software Reliability Growth とかでひっかかります。

■_

2012年03月05日

■_

ふーむこういうこともできるのね。 Kindle向けニュース配信システムをHeroku上に移動した - ただのにっき(2012-03-04)

アレに行ってきたんですがまとめやら書くの面倒…

■_ Student Questions about Scala, Part 1

一部だけ抜き出し。

Student Questions about Scala, Part 1 - Java Code Geeks

Monday, 27 February 2012
Student Questions about Scala, Part 1

Preface

I'm currently teaching a course on Applied Text Analysis and am using Scala as the
programming language taught and used in the course. Rather than creating more tutorials,
I figured I'd take a page from Brian Dunning's playbook on his Skeptoid podcast (highly
recommended) when he takes student questions. So, I had the students in the course submit
questions about Scala that they had, based on the readings and assignments thus far. This
post covers over half of them — the rest will be covered in a follow up post.

I start with some of the more basic questions, and the questions and/or answers
progressively get into more intermediate level topics. Suggestions and comments to 
improve any of the answers are very welcome!

Basic Questions

Q. Concerning addressing parts of variables: To address individual parts of lists, the 
numbering of the items is (List 0,1,2 etc.) That is, the first element is called “0″. It
seems to be the same for Arrays and Maps, but not for Tuples- to get the first element of a
Tuple, I need to use Tuple._1. Why is that?

変数の addressing parts について。
リストの individual parts を指定するのにその要素の番号は (List 0,1,2 etc) のように
なっています。つまり、最初の要素は“0”です。
これはArrayでもMapでも同じように思われます。
しかし、Tuple は違っていて、その最初の要素を得るのには
Tuplle._1 を使わなければなりません。これはなぜですか?


A. It's just a matter of convention — tuples have used a 1-based index in other languages
like Haskell, and it seems that Scala has adopted the same convention/tradition. See:

これは convention の問題です。
tuple ではHaskell のような他の言語と同じ 1-based index を採用しています。


http://stackoverflow.com/questions/6241464/why-are-the-indexes-of-scala-tuples-1-based


Q. What is the major difference between foo.mapValues(x=>x.length) and foo.map(x=>x.length).
Some places one works and one does not.

foo.mapValues(x=>x.length) と foo.map(x=>x.length) との大きな違いとはなんでしょうか?
片方が動作しもう片方が動作しないケースがあります。

A. The map function works on all sequence types, including Seqs and Maps (note that Maps
can be seen as sequences of Tuple2s). The mapValues function, however, only works on Maps.
It is essentially a convenience function. As an example, let's start with a simple Map
from Ints to Ints.

map 関数は Seqs や Maps を含みすべての sequence 型に対して動作します。
しかし mapValues 関数は Maps に対してのみ動作します。
mapValues は本質的には convenience 関数なのです。
例として、単純な Ints から Ints への Map から始めましょう


	scala> val foo = List((1,2),(3,4)).toMap
	foo: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4)


Now consider the task of adding 2 to each value in the Map. This can be done with the 
map function as follows.

ここで、Map されているそれぞれの値に2を加えることを考えてみましょう。
これは map 関数を使って次のように書けます

	scala> foo.map { case(key,value) => (key,value+2) }
	res5: scala.collection.immutable.Map[Int,Int] = Map(1 -> 4, 3 -> 6)

So, the map function iterates over key/value pairs. We need to match both of them, and 
then output the key and the changed value to create the new Map. The mapValues 
function makes this quite a bit easier.

ですから、この map 関数は key/value のペア群に対して iterates over しているのです。
ペアの両方にマッチさせる必要があり、それから 新しい Map を生成するために
key と新しく作った value を出力します。
mapValues 関数はこういった操作をとても簡単なものにします

	scala> foo.mapValues(2+)
	res6: scala.collection.immutable.Map[Int,Int] = Map(1 -> 4, 3 -> 6)

Returning to the question about computing the length using mapValues or map — then it 
is just a question of which values you are transforming, as in the following examples.

mapValues や map を使った長さを計算についての質問に戻りましょう。
この質問はつまり、以下の例のようにあなたが transforming しようとする値に関するものです。


	scala> val sentence = "here is a sentence with some words".split(" ").toList
	sentence: List[java.lang.String] = List(here, is, a, sentence, with, some, words)
	 
	scala> sentence.map(_.length)
	res7: List[Int] = List(4, 2, 1, 8, 4, 4, 5)
	 
	scala> val firstCharTokens = sentence.groupBy(x=>x(0))
	firstCharTokens: scala.collection.immutable.Map[Char,List[java.lang.String]] = Map(s -> List(sentence, some), a -> List(a), i -> List(is), h -> List(here), w -> List(with, words))
	 
	scala> firstCharTokens.mapValues(_.length)
	res9: scala.collection.immutable.Map[Char,Int] = Map(s -> 2, a -> 1, i -> 1, h -> 1, w -> 2)

Creative Commons License
This work by Java Code Geeks is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

■_

2012年03月04日

■_

つながらない生活 ― 「ネット世間」との距離のとり方
つながらない生活 ― 「ネット世間」との距離のとり方
を読んだのですが、最後の方で
パタン・ランゲージ―環境設計の手引
パタン・ランゲージ―環境設計の手引
が本文中に出てきたりでこっちも読みたくなった…けど高いんだよなあ。 この金額出すなら他に買いたいものがげふんげふん

内容の方ですが、まあタイトルから予想できる通り(笑) 過去の技術革新と絡めていろいろ書かれてます。 まるごとネット環境を否定しているのではなく、どのように付き合うかを考えよう という感じでしょうか。

■_ 今日の十個ネタ

すべてのJava developer が Groovy を学ぶべき理由。

例によって項目だけ抜き出します。

Ten Reasons Every Java Developer Should Learn Groovy (Part 1) | Streets Ahead LLC

Ten Reasons Every Java Developer Should Learn Groovy (Part 1)
by Sam Mussell

This is part one of my two part post on some of the many reasons that a modern Java developer
really should take an hour and learn Groovy. It really is the age of the polyglot programmer,
and there are a ton of new and interesting languages on the JVM. Of all those JVM languages
I dare to say Groovy is the closest tied to Java, so it offers a ton of advantages with a
more gentle learning curve for a Java developer than some other JVM languages.

ありゃ、前半だけか

■_ Why C is a good language - or why you're wrong thinking C++ is better

なぜCが良い言語なのか。あるいはC++がより良い言語と考えるのがなぜ間違いなのか

Why C is a good language - or why you're wrong thinking C++ is better - Grumpycoder

Why C is a good language - or why you're wrong thinking C++ is better

By Pixel on Friday, March 2 2012, 09:01

I've recently had a discussion with some friends over at Google+ which finally made me 
understand why there's so many people out there who don't understand why C is superior to
C++, even though there's so many people who say so. So let me share this epiphany with you.

The reason why some programmers think C++ is superior to C is because they're bad
programmers. Alright, let me rephrase this so you don't immediately start flaming me. The
reason why some programmers think C++ is superior to C is because they (most of the time)
don't have the same mindset. And if they do have the same mindset as pro-C people, then
they are not aware that there's people out there who don't. But allow me to develop.

略
In conclusion, if you don't like C, and prefer more modern languages, then I'm not saying
you're a "bad" programmer as it's very probably you'll write code that is pretty,
and runs nifty GUIs and even may be useful. However, I'm saying that if you don't see the
advantages of C over other languages, then it means you don't clearly understand the
philosophy behind C, and what it actually means to write code that's going to be as
efficient as possible. Start learning about compilers. Learn about assembly. Learn about
processors, cache lines, and other branch-predictions thingies. Then you'll understand why
C is superior.

なんか訳すのが憚れる様なこと書いてるなw

んで、じゃあアセンブリ言語を理解しているプログラマーの方が、いやいやハードウェアを… というツッコミ多数。

■_ エレガントな回答求む

Does anyone have a more elegant solution for this practice problem? : Python

Link to problem: http://codingbat.com/prob/p143951

Description: Given 3 int values, a b c, return their sum. However, if one of the 
values is the same as another of the values, it does not count towards the sum.

三つの int a, b, c が与えられ、その合計値を返す。
ただし、ある値がほかの値の同じであった場合それは合計には反映されない。

  lone_sum(1, 2, 3) → 6 lone_sum(3, 2, 3) → 2 lone_sum(3, 3, 3) → 0

The following logic tree is what' I'm calling the 'inelegant' solution:

  def lone_sum(a, b, c):
    if a == b == c:
      return 0
    elif a == b:
      return c
    elif a == c:
      return b
    elif b == c:
      return a
    else:
      return a + b + c

Any ways to solve this using array functions or something more elegant than a tedious 
logic tree? I don't accept that the logic tree is the only solution as if there were 5 
or 10 values that needed to be compared this way, the logic tree wouldn't be practical.

Thanks!

*edit: added the code for the logic tree as the less-than-optimal solution

Here is my solution:

  def lone_sum(*args):
      return sum([x for x in args if args.count(x) == 1])    


You could leave out those square brackets if your fingers were getting tired, leaving 
you with a generator expression instead of a list comprehension.
  import collections
  def lone_sum(*args):
      c=collections.Counter(args)
      return sum(k for k,v in c.iteritems() if v==1)

I think collections.Counter was added in 2.7.


  def lone_sum(*args):
      d = dict()
      for i in args:
          d[i] = 1 if i not in d else 0
      return sum([k for k in d if d[k]])

I like this one best so far; only a nit-picking:

  def lone_sum(*args):
      d = dict()
      for i in args:
          d[i] = (i not in d) # here
      return sum([i for i in d if d[i]])


assuming you think you can just sum the set of the args, i rebuke thee since you cannot
count either instance of the dupe... there is a solution that is set-oriented, though:

  def lone_sum(*args):
      sargs = set(args)
      dargs = set([a for a in args if args.count(a) > 1])
      return sum(list(sargs-dargs))

  def lone_sum(*args):
     return sum(set(args))


  def lone_sum(a, b, c):
      return (a * int(a!=b) * int(a!=c)) \
          + (b * int(a!=b) * int(b!=c)) \
          + (c * int(a!=c) * int(b!=c))

  def lone_sum(*args):
      return sum([
          operand * int(operand not in args[:i]+args[i+1:])
          for i, operand in enumerate(args)
          ])


  def lone_sum(*args):
     counts = collections.Counter(args)
     return sum(x for x, c in counts.items() if c == 1)

edit just noticed maxerickson came up with the same solution before me


  def sum_unique(*args):
    uniques = set(args)
    return sum(uniques) if len(uniques) > 1 else 0

  def lone_sum(a, b, c):
      nums=[a,b,c]
      return sum([nums[x] for x in range(0,3) if nums[x] != nums[(x-1)%3]
                  and nums[x] != nums[(x+1)%3]])


Here's my terribly convoluted solution (Hillmanov's solution is the most pythonic here):

  def lone_sum(a, b, c):
      values = [a, b, c]
      map = {0: True, 1: True, 2: True}
      counter = 0
      innerindex = 0

      for value in values:
          index = values.index(value)

          if values.count(value) != 1:
              for innervalue in values:
                  if innerindex != index and innervalue == value:
                      map[innerindex] = False
                      map[index] = False
                      break

                  innerindex = innerindex + 1

          if map[index] != False:
              counter = counter + value

      return counter


Heres a python 1 liner in function format:

  lone_sum = lambda *args: sum([i*(args.count(i)==1) for i in set(args)])

It's ugly, but:

def lone_sum(*args):
    arg_set = set()
    removed_set = set()
    the_sum = 0
    for arg in args:
        if arg in removed_set:
            continue
        elif arg in arg_set:
            the_sum -= arg
            removed_set.add(arg)
        else:
            the_sum += arg
            arg_set.add(arg)
    return the_sum


On phone, so not 100% sure it's bug free, but would this work?

  def foo (a, b, c):
      N = {}
      for x in [a, b, c]:
          # could do this and/or style, I guess
          if x in N:
              N[x] = N[x] + x
          else:
              N[x] = x
      return sum([N[k] for k in N if N[k] == k]}


  def index(listhere, var):
      return [i for i,n in enumerate(listhere) if n == var]

  def lone_sum(a, b, c):
      temp = [a,b,c]
      if len(index(temp,a)) > 1:
          return sum(temp) - a*len(index(temp,a))
      elif len(index(temp,b)) > 1:
          return sum(temp) - b*len(index(temp,b))
      else:
          return sum(temp)


A general solution.

  def lone_sum(*args):
      numbers = set(args)
      for i in args:
          if args.count(i)>1 and i in numbers:
              numbers.remove(i)
      return sum(numbers)

Something like this,i'm on mobile and can't check:

  import itertools

  def lone_sum(*args):
    elems = itertools.groupby(sorted(args))
    return sum( elem for elem, count in elems if count == 1)

■_ 今日のモナド

関数型言語Part5

712 デフォルトの名無しさん [sage] 2012/03/03(土) 15:59:16.17 ID: Be:
    なんで人はモナドで躓くんだろ? 

713 デフォルトの名無しさん [sage] 2012/03/03(土) 16:20:37.82 ID: Be:
    >>712
    いまHakellを勉強する人は良くも悪くも「意識の高い」人だから、
    「モナドは圏論から来た概念で~」とか言われると、数学の勉強を始めてしまうから。

    「doと<-はおまじないです」でかまわない人が増えたら、つまづかなくなるだろ 

714 デフォルトの名無しさん [sage] 2012/03/03(土) 19:17:12.43 ID: Be:
    >>713
    それが躓く理由なら、OCamlでモナドを定義しても相変わらず躓くな
    圏論から来た概念なことには違いないのだから、言われれば数学の勉強を始めるのだろう 

715 デフォルトの名無しさん [sage] 2012/03/03(土) 19:20:28.52 ID: Be:
    しかし、Haskellそっちのけで数学の勉強を始めてしまうのは躓くとは違うな
    何も躓いていない

    むしろスムーズにHaskellから数学に移行している
    そこからのまたHaskellに滑らかにUターンしてこればいい

    従って、躓く原因は他にあるな 

716 デフォルトの名無しさん [sage] 2012/03/03(土) 19:55:28.28 ID: Be:
    >>712
    >なんで人はモナドで躓くんだろ?

    そこにモナドがあるから

    一般的な手続き型言語/オブジェクト指向言語は
    正格評価(非遅延評価)を採用し、副作用(入出力や破壊的代入)を前提にしている
    だからそういった言語に慣れた「ふつうの」プログラマにとって、
    正格評価や副作用は潜在意識下に存在し、それが自然なものであると(無意識に)理解している

    それがHaskellでは、わざわざモナドを使わなければまともなプログラミングできない
    言い換えると、ふつうのプログラマにとって、モナドの存在そのものが「異質」に見える 

717 デフォルトの名無しさん [sage] 2012/03/03(土) 20:04:46.41 ID: Be:
    >>712
    俺的にはモナド使うと誰得なんですか的なところがつかめんかった。
    HaskellerじゃないのでIOモナドはあまり関係ないし。
    今は書いてあるコードの後ろにゴニョゴニョした部分を後ろにおっつけられるようにフックしつつデータをたらい回せる機能という理解になってしまってる。
    のでFunctor→Applicative→Monadの発展の流れってのをイマイチ理解してないよ・・・

718 716 [sage] 2012/03/03(土) 20:58:15.37 ID: Be:
    一部訂正

    X: それがHaskellでは、わざわざモナドを使わなければまともなプログラミングできない
    O: それがHaskellでは、わざわざモナドを使わなければ実用的なプログラミングができない 

719 デフォルトの名無しさん [sage] 2012/03/03(土) 21:02:45.49 ID: Be:
    表示的意味論で繰り返し使われる手法を
    抽象化してまとめたのがモナド。
    意味論から出たデザインパターン。
    ボトムアップ一辺倒の人は分からない概念。
    うまくまとめたってだけで、なくてもなんとかなるから。 

720 デフォルトの名無しさん [sage] 2012/03/03(土) 21:13:07.25 ID: Be:
    >>717
    > 俺的にはモナド使うと誰得なんですか的なところがつかめんかった。

    モナドを「わざわざ」って思ってしまうのは、入門書に載っているような、
    ターミナル相手の入出力の使い方しか知らないからだと思うんだ

    たとえば Web フレームワークの Yesod で Web ページを定義する時、
    ヘッダやフォームなどの部品は全てモナドなんだが、
    わざわざなんて感じは無く、かなり自然に記述できる
    そこでは、「順序を意識すること無く宣言的に記述する」
    ためにモナドが利用されている

    wx で GUI の見た目を定義する場合もモナドを使うが、
    ほとんど宣言的に記述できるように工夫されてる
    (本当は DnD なんかもっとモナドを活用して宣言的に書けるはずなんだが、
    今は未だライブラリで提供されてはいないな)

    こういうモナドの活用例とその仕組みを入門書で知る事ができれば、
    躓く人も少しは減ると思うんだ

721 デフォルトの名無しさん [sage] 2012/03/03(土) 21:23:35.66 ID: Be:
    手続き型言語の世界には、
    ・プログラム = アルゴリズム + データ構造
    という有名な言葉がある
    これをHaskell流に見立てると、以下のようになる
    ・プログラム = 数式 + 代数的構造
    つまり、「Haskellプログラミングとは数学的活動である」と見なすことができる

    更には、Haskellには無限リスト、リスト内包表記、ガード、インデントベースといった
    数学固有の記述法に適した構文が巧妙に組み込まれているから、
    こうした数学的素養のある人にとって、Haskellはこのうえもない関数型言語に感じるはず

    また>>715はモナドに関するカキコだけど、より一般的に解釈すれば、
    初心者がHaskellを触るによって「数学的活動としてのプログラミング」の第一歩を
    自然と歩むことになることを意味する
    これは「正しい」プログラミング設計作法を学ぶためには、とても好ましい道筋だと思う 

741 あたりから再燃してるけどそっちはカット。

■_

■_ Hums

Humus
Humus 

Humus is a pure actor-based programming language that provides a foundation for software
developers to build reliable concurrent computer systems. It features a referentially
transparent pure-functional core for defining values. These values become the messages
between (and specify the behavior of) dynamically configured actors. 

Hums は reliable な並列コンピューターシステムを構築する software developer 向けの
foundation を提供する pure な actor ベースプログラミング言語です。
値を定義するための参照透明 (referentially transparent) な pure-functional な core があります。
定義された値は動的に configure された actor 間のメッセージとなります
(そして actor の動作を指定します)。

Actor behaviors are composed of concurrent, rather than sequential, primitive operations.
Groups of actors, called configurations, may also be composed without affecting their
operation. This allows implementation of systems with high scalability and low latency in
both multi-core and distributed execution environments. 

actor の振る舞いは直列にではなく並列に compose される primitive operation です。
actor の集まりは configrations と呼ばれ、その operation に影響を及ぼすことなく
compose することもできます。これはマルチコア環境や分散実行環境の両方における
high scalability と low latency を備えたシステムの実装を可能とします。

The theoretical foundations of Humus have mathematically rigorous semantics. Unlike Erlang
or Scala, there are no blocking operations and all expressions are completely free of
side-effects. Mutable state is entirely encapsulated within actors and may be affected only
by sending asynchronous messages. 

actor もずいぶん昔から名前だけは聞きますよねえ。 いよいよ?

mathematically rigorous semantics ってなんだろう…

2012年03月03日

■_

・航空戦隊

・HOPL I II
タレコミがあったFORTRANの変数名のあれ (I, J, K の話ね)なんですが、 HOPL I に収録されてるみたいですねえ。 I も II も買ったはずなんだけどさてどこに行ったやら (BASICのところは結構熱心に読んだんだけど FORTRAN はスルーしてたような覚えが)

遅延評価ってなんなのさ - 予定は未定Blog版

■_ 刷り込み

次からあの曲聴いてもこれを思い出してしまいそうな気がするw

山田芳裕 『へうげもの』 第九十九席

245 名無しんぼ@お腹いっぱい [sage] 2012/03/02(金) 22:26:17.02 ID:S5unoAG20 Be:
    最近いきつけの店とか入るとBGMに有線かなんかで若い女子の歌が流れてるんだけど、
    フライングゲットなる言葉を連呼する歌が流れてきて、
    その歌が流れているあいだずっと
    ゲヒ殿が平蜘蛛の蓋をじゃんぴんぐキャッチしている図しか浮かばなかったんだ。 

■_ The Heroes of Java

12人目か。何人か抜けたような気がするけど追いかけてるわけでもないからいいや

Enterprise Software Development with Java: The Heroes of Java: Ward Cunningham

Monday, February 13, 2012 

The Heroes of Java: Ward Cunningham 
 
The 12th part of my "Heroes of Java" interview series is somehow, let's call 
it special. It's not about an active member of the Java community in the sense of a 
well known evangelist, programmer or speaker. It's more about someone providing 
essential backgrounds in both methodology and tools for our daily work. And I am very 
glad to have him in the series. 
 
Howard G. "Ward" Cunningham 

(略)

You're programming in Java? Why? 

I find Java libraries hard to grok but likely to deliver when you finally get into them.
2D Graphics, for example. 
 
I once wired the Rino JavaScript interpreter into Eclipse to make a Greasemonky like 
extension system. It could even dynamically load Java modules when it discovered that 
JavaScript wanted them. Every hook I need was in the libraries and documented too. 
Java, Rino and Eclipse all deserves kudos of that sort of attention to details. 

以前に、わたしは Greasemonky のような拡張システムを持ち込むために
Rino JavaScript インタープリターを Eclipse に組み込んだことがあります。
そのシステムでは JavaScript が必要とした Java のモジュールを動的にロードすることもできました。


I have a lot of respect for the JVM. It provides a widely available platform with 
memory and process abstractions that has raised the general level 
 
I will admit to being drawn to less demanding languages, ones where "hello world"
can be written in one line, or maybe two. 

I like to judge a language by the density of leveraged operations. Smalltalk code 
would do two or three leveraged operations per line. Perl does one or two. C does 
maybe one if it is written in the old K&R style, much less now. Java is down at 
the same level as C: two or three lines for every leveraged operation. That hurts. 

わたしは言語をその density of leveraged operations (レバレッジ操作の度合い?) で
判断するのが好きです。Smalltalk のコードは一行辺り二つか三つの leveraged operation
を行います。Perl では一つか二つの leveraged operation を行います。
C はおそらく、古い K&R で書かれていたとしてひとつ、現在でも似たようなものでしょう。
Java は C と同レベルの代物で、leveraged operation ごとに二行とか三行要します。

What's least fun with Java? 

If I can't get the paths right in a half an hour I give up and go on to something else. 

I'm no fan of XML either. It seems overused in many Java systems. I like to say that 
JSON is a representation while XML is a career path.
わたしは XML が好きではありません。
Java システムではXMLを使いすぎているように思います。
XML が career path なのに対して JSON は representation なのではないでしょうか

If you could change one thing with Java, what would that be? 

I wrote a class called TypeAdapter in FIT. It was suppose to be the stand-in for the 
universal format converter that I just assumed every big project would develop. I'm 
still annoyed that it was so hard to write and that so few people understood the value 
of collecting this responsibility into a single place. 
 
What's your personal favorite in dynamic languages? 

I'm liking CoffeScript, mostly because it makes JavaScript's callback-style tolerable. 
 
Which programming technique has moved you forwards most and why? 

I try to make code look like it was easy. That's a sure sign that I understand what a 
programming language or framework has to offer and I've applied it to my problems well. 
I like to know the power moves but want to show that I don't have to keep using them 
to get the job done. Most influential was a week long class I once took taught by one 
of Dijkstra's students. We were told that we would just look at beautiful programs 
throughout the week but first he would teach us how to appreciate them. You can get a 
hint of what that week was like by reading Dijkstra's Discipline of Programming. 
 
Making a new language is the ultimate power move. There are lots of ways to do it. Get 
to know them all A switch statement inside a for loop makes an interpreter. When you 
write that, ask yourself: what language am I interpreting? 
 
Copyright © 2007-2011 by Markus Eisele.. Powered by Blogger. 

びみょーに日本語にしづらいな(自分の実力では)

■_

組み込むことを念頭に置かれて開発されたプログラミング言語って Tcl 以前にありましたっけ?

iRules Concepts: Tcl, The How and Why > DevCentral > Tech Tips on DevCentral

F5 uses Tcl as the interpreter for iRules. Many people often ask why that is. This 
questions is usually followed up by an immediate, "Why not Perl?" or 
"Why not Java" or "Why not <fill in my preferred language of choice>?".
I understand the question, and frankly I'm a Perl guy from way back myself, so when I first
landed at F5 and started devouring all things iRules, I was curious about the same thing.
Since then I've discussed this topic with some of F5's best, in my opinion, and have come
to understand that there are many solid reasons for choosing the runtime that we use.

F5 は iRules のためのインタープリターとして Tcl を使っています。
多くの人がなぜ Tcl なのかと頻繁に尋ねてきます。
そしてその直後に、「なぜ Perl を使わないんですか?」、「なぜJavaを使わないんですか?」、
「なぜ (あなたの好きな言語をここにどうぞ) を使わないんですか?」
といった質問が続くのです。
そういった質問をするのは理解できますし、わたし自身が Perl 使いでもあります。
ですからF5 にきて最初に iRules に携わったときには同様の疑問を抱きました。
それから F5 の best 何人かと議論したのですが、
Tcl を使う確たる理由があるのだということが理解できました。


When asked "Why Tcl?" my standard response centers around varying degrees of 
discussing:

    • Speed

    • Embeddability

    • Usability

以下略

各項目の詳細な説明は元記事をどぞ (結構長いので訳すのはくじけたw)

■_

Common Lisp has no future とか

Clojure/core — (take 5 william-byrd)

(take 5 william-byrd)
Posted by michael fogus on Feb 16, 2012

William Byrd is a postdoc at Indiana University researching the applicability of 
declarative programming techniques to high-performance computing domains. In addition, 
he is one of the three authors of the fantastic book The Reasoned Schemer that walks 
the reader through the development of a small but powerful logical programming system 
in Scheme called miniKanren. Dr. Byrd attended the 2011 Clojure Conj and gave (along 
with Dr. Friedman) what became one of the best talks of the conference -- during the 
conference off hours. In this candid installment in the (take) series of 
micro-interviews Dr. Byrd discusses Clojure, Scheme, Lisp, macros, and miniKanren's 
evolution.

(さっくり略)

How do you see the future of Lisp progressing?

Common Lisp has no future--if taking the union of features from multiple Lisp Machine 
implementations didn't kill it (why have one object system when you can have three?), 
standardization did. Fortran is still evolving; Common Lisp isn't.

Common Lisp には未来はありません。複数の Lisp マシンの機能をまとめてみても、
それ (Lispマシン?) を葬ることはできません(三種類のオブジェクトシステムがあるときに
ひとつだけを使ったりするでしょうか?)。それは標準化が行うことです。
Fortran は今でも進化し続けていますが、Common Lisp は違います。

So far the Scheme community has avoided making the same mistakes. Historically, only 
the intersection of features from the major implementations have made it into the 
standard. The result is a standard language that is useless for real-world programming 
(FFI and threads aren't in the current standard, for example) but encourages researchers
and implementers to experiment with new features. In fact, Scheme shouldn't be viewed as
a complete programming language--rather, Scheme is a dialect of Lisp, and the various
implementations (Racket, Chez, Ikarus, etc.) are dialects of Scheme. Scheme will never
become a popular language, but popular languages are becoming more like Scheme. For
example, Ruby ripped off much of Scheme--alas, Matz decided not to rip off the most
important part, hygienic macros, which is why Ruby programmers think the solution to
every problem is to hack the interpreter.

以下略
Clojure/core ©copyright 2010 - all rights reserved.

■_ C99

"Microsoft, please support (at least a tiny bit of) C99 : programming"

Microsoft, please support (at least a tiny bit of) C99 | Josh Haberman

Microsoft, please support (at least a tiny bit of) C99
Posted on March 2, 2012 by Josh	

I'm afraid this plea will be mostly futile, but I just have to get it out. Microsoft, 
please support (at least a tiny bit of) C99.

Though it may seem strange, there are still a lot of us writing in C (and not C++), 
particularly in the open-source world. For example, all of the following very important
open-source projects (which all are portable to Windows) are written either partially
or entirely in plain C:

驚くことかもしれませんが、特にオープンソース世界では (C++ ではなく) C で書かれたものが
まだまだたくさんあります。たとえば以下に挙げたような非常に重要なオープンソースプロジェクト
(どれも Windows に移植可能です) は全体でなくとも部分的には plain な C で書かれています。


    almost every open-source language VM (eg. Python, Lua, LuaJIT, Ruby, Perl, PHP, Erlang, R, Guile)
    ほぼすべてのオープンソース言語の VM

    numerous very powerful software libraries (eg. zlib, sqlite, libmad, ffmpeg/libavcodec,
    x264, libsndfile, libsamplerate, gmp, fftw, libxml2, FreeType, libjpeg, libpng; this list
    is just the tip of the iceberg, there are way too many to list).

    非常に強力なソフトウェアライブラリの数々

    numerous apps/tools/servers (eg. Apache, nginx, vim, emacs, MySQL, PostgreSQL)
    多くのアプリケーションやツール、サーバー


The reason you offer for not adding C99 support is
Microsoft が C99 のサポートを追加しない理由というのはこうです

    Hi: unfortunately the overwhelming feadback we get from the majority of our users is that
    they would prefer that we focus on C++-0x instead of on C-99. We have “cherry-picked”
    certain popular C-99 features (variadic macros, long long) but beyond this we are unlikely
    to do much more in the C-99 space (at least in the short-term).

    C99 よりも C++0x に関する要望の方がたくさんあるのよ。残念ながら。
    それと、C99 のいくつかの popular な機能はサポートしているのだけど
    C99 をサポートするには少なくとも短期間では手に負えないような手間がかかるのね。
    #とちょー訳

It may be that we C users are in the vast minority. But considering that we have been 
offering free, high-quality software that enhances the usefulness of the Windows 
platform for both users and developers, couldn't you help make our job just a little 
easier by implementing even these most basic C99 features?

わたしたち C ユーザーは極少数な存在なのかもしれません。
しかし、わたしたちが offer している Windowsプラットフォームの
ユーザー向け、developers 向けの usefulness を
拡大するような free で high-quality なソフトウェアを考慮して、
わたしたちの仕事をほんの少し簡単にするために
以下のもっとも基本的な C99 の機能だけでも実装してもらえないでしょうか?

    stdint.h and inttypes.h. Someone else has already done the work for you and released it
    under a permissive license (stdint.h and inttypes.h). Can't you just download these
    files and use them?

    stdint.h と inttypes.h。すでにこれのための作業をした人がいるので、permissive な
    ライセンスの元でリリースできるでしょう、
    あなたがたはこれらのファイルをダウンロードして使うこともできないのでしょうか?

    declaring variables in the middle of a block. Your C++ compiler can already do this,
    surely it wouldn't be too much work to update the C parser to support this?

    ブロック途中での変数宣言。Microsoft の C++ コンパイラーは既にこれが可能なのですから、
    C のパーザーがサポートするように変更するのはそれほどの手間ではないのでは?

    ‘for' loop initial declarations. This is also supported in C++ already.

     'for' ループでの initial decrations。これも C++ ではすでにサポートされているものです。

If I was feeling really lucky I might even ask for designated initializers, but I don't want
to push my luck.

Every other popular C compiler supports these features, which means that for many projects
MSVC's lack of C99 support is the single gating factor keeping us from taking advantage of
features that were standardized almost 15 years ago. Think about this: a large and diverse
project like Python which might have tens of committers and run on lots of platforms is
tethered to an almost 25-year-old language standard (C89) because one single compiler that
is written by one of the world's largest software companies (with over 90,000 employees)
can't find the time to do what every other compiler vendor has already done.

ほかの popular なCコンパイラーはみなこれらの機能をサポートしています。
これがどういうことかといえば、多くのプロジェクトにとって MSVC の C99 サポートの欠如が
15年以上前に標準化されているはずの機能による利点を得ることを邪魔するものになっている
ということなのです。
Python のような規模が大きく diverse なプロジェクトは多くのコミッターとプラットフォームを
抱えているのに、
ほかのコンパイラーベンダーがとっくにサポートしている機能をサポートする時間もないと主張する
世界最大のソフトウェア会社によるたった一つのコンパイラーがあるために
25年前の言語標準 (C89) に従わなければならないのです。
#かなり無理やり

As I was researching this article I discovered that the /TP option will make MSVC compile
C as if it were C++, which may give me enough of a workaround (albeit hacky) to get the
above features that I most sorely miss. I still wish Microsoft would give us cross-platform
developers even the slightest tip of the hat to help us out with bringing free, high-quality
software to their platform.

すでにわたしが調べているように、C で書かれたソースコードを C++ であるかのように
MSVC にコンパイルさせる /TP オプションがあります。
これは前述の機能がないことのワークアラウンドには十分なのですが、
わたしは Microsoft が

C99 をサポートしてないVCのために ××を修正して欲しいとお願いするのは疲れたっす。わたしも。 自分で修正するのもかw

■_

2012年03月02日

■_

Hacker News でわりと話題になることが多いのだけど、 直接追いかけた方がいいのかな(あんまりチェックするのを増やすのもあれだけど) Give it five minutes - (37signals)

■_ 2011

β。

Visual Studio 2010 Part18 

673 デフォルトの名無しさん [sage] 2012/03/01(木) 10:26:53.05 ID: Be:
    VS11beta早速入れたけど、インターフェースはこんなモノトーンなのか。
    色付きのアイコンが稀にある程度なんだけど、インストールに失敗したわけじゃないよなw 

676 デフォルトの名無しさん [sage] 2012/03/01(木) 12:17:50.41 ID: Be:
    前VS2010β入れておかしくなったから
    VS11βはサブマシンに入れたいんだけど
    XPでは使えないのかよ 

678 デフォルトの名無しさん [sage] 2012/03/01(木) 13:41:46.59 ID: Be:
    >>676
    確か、"VS11はXPサポート外" だったと思ったけど。
    ---
    すっぴんのXPにVS2010入れてみたけど、何やらワーニングが・・・
    .NET3.5も入れたらワーニング消えたけ。

    どうも、オマケデ付いてくる .NET4 だけじゃ駄目みたいだな。 

679 デフォルトの名無しさん [sage] 2012/03/01(木) 15:06:33.11 ID: Be:
    XPはオワコン 

680 デフォルトの名無しさん [sage] 2012/03/01(木) 15:12:43.96 ID: Be:
    11の起動の重さは2010と変わらず? 

681 デフォルトの名無しさん [sage] 2012/03/01(木) 16:18:35.02 ID: Be:
    C++CLRのインテリセンス復活。 

682 デフォルトの名無しさん [sage] 2012/03/01(木) 17:01:46.08 ID: Be:
    http://www.microsoft.com/visualstudio/11/ja-jp
    http://msdn.microsoft.com/subscriptions/downloads/

    11のスレは無いのか 

683 デフォルトの名無しさん [sage] 2012/03/01(木) 18:37:15.44 ID: Be:
    >>676 >>678
    XPは、単にMSのサポートが受けられないというだけじゃなくて、
    インストールすらできないってこと?

    >>682
    11スレ立ておねがい 

684 デフォルトの名無しさん [sage] 2012/03/01(木) 19:30:59.69 ID: Be:
    11インストール途中でエラー出て止まった(;´д` )
    OSから入れ直すしかないのか… 

685 デフォルトの名無しさん [sage] 2012/03/01(木) 19:58:18.03 ID: Be:
    今年は2012なのになんでVS11なんだ?
    VSも年じゃなくバージョンを名前にするようになったのか 

687 デフォルトの名無しさん [sage] 2012/03/01(木) 20:13:26.37 ID: Be:
    Visual Studio 11 って正式名称なの?
    つかベータ版でスレ立てっておかしいだろ。 

688 デフォルトの名無しさん [sage] 2012/03/01(木) 20:14:15.11 ID: Be:
    いや別に 

689 デフォルトの名無しさん [sage] 2012/03/01(木) 20:17:52.93 ID: Be:
    立てといた
    ttp://toro.2ch.net/test/read.cgi/tech/1330600614/ 

690 デフォルトの名無しさん [sage] 2012/03/01(木) 20:38:30.94 ID: Be:
    なんでここバージョン別にスレ建てたがるんだ
    どうせ最新版スレで聞くのに 

691 デフォルトの名無しさん [sage] 2012/03/01(木) 20:51:13.76 ID: Be:
    >>683

    システム要件
    サポートされるオペレーティング システム
    Windows 7 (x86 および x64)
    Windows 8 Consumer Preview (x86 および x64)
    Windows Server 2008 R2 (x64)
    Windows Server 8 Beta (x64)
    --- 

692 デフォルトの名無しさん [sage] 2012/03/01(木) 22:11:45.16 ID: Be:
    ひでーなVistaまで蚊帳の外かよw さすがに製品版ではサポートされると思うが…
    ハードウェア要件にはDirectX9ってあるからXPでも動くかも? 

693 692 [sage] 2012/03/01(木) 22:12:59.74 ID: Be:
    あーなるほどサポートしないけど動くってパターンかな 

694 デフォルトの名無しさん [sage] 2012/03/01(木) 22:51:01.43 ID: Be:
    >>692
    メインターゲットである企業は XP ⇒ 7 だから、Vista 非対応は充分ありえると思うぞ。 

695 デフォルトの名無しさん [sage] 2012/03/02(金) 03:18:16.48 ID: Be:
    >>694
    正式版リリース時にはもう、Vistaはサポートフェイズが… 

696 デフォルトの名無しさん [sage] 2012/03/02(金) 10:43:37.11 ID: Be:
    >>691
    それは公式サポートするOSですよね

    サポート外だけど技術的に問題なくインストールできるのか、
    それともインストール自体がはじかれるのか、
    聞きたかったのはそういう技術的に動くかってことです。

    >>695
    Vistaはサポート期間が大幅に延長されたよ
    2017 年 4 月 11 日。
    http://www.microsoft.com/ja-jp/windows/lifecycle/default.aspx 

697 デフォルトの名無しさん [sage] 2012/03/02(金) 13:30:29.39 ID: Be:
    >>696
    .NET Framework 4.5 が駄目くらいなんだから、まぁ無理だろ。 

698 デフォルトの名無しさん [sage] 2012/03/02(金) 15:04:12.53 ID: Be:
    >>696
    そうじゃなくて今のMicrosoftは、
    メインストリームサポートから外れると、
    新機能とか追加しないことがほとんど

    前回XPに .net 4.0 対応させたのには正直意外だった

さてどうするかねえ。 ノートもデスクトップもいい加減替え時なんだけど以下略

■_ Bug

しばらく追いかけてなかったら、先月この話題で結構やり取りがあった模様。

[PATCH 1/3] sed: Fix infinite loop on some false multi-byte matches

From: 	Stanislav Brabec
Subject: [PATCH 1/3] sed: Fix infinite loop on some false multi-byte matches
Date: Fri, 10 Feb 2012 20:39:37 +0100

sed may hang in an infinite loop on some strings in charsets that form a
false match on a boundary of two characters (e. g. EUC-JP) replacements.

The execute.c: str_append() makes bad assumption:

if (n > 0)

n is declared as size_t. And on glibc in Linux x86_64, size_t seems to
be defined as unsigned long. The code apparently does not expect that it
is true for -2 as well.

Further bug is a bit deeper, and may require fix of the same code in
glibc, depending on configure parameters. See
http://sourceware.org/bugzilla/show_bug.cgi?id=13637 for glibc fix.

re_search_internal() inside switch(match_kind) in case 6 finds a
possible match. In case of our false match, verification of match not
respecting multi-byte characters fails and match_regex() returns index
of such false match.

Going deeper, re_search_internal() calls re_string_reconstruct() and
that calls re_string_skip_chars().

re_string_skip_chars() is a I18N specific function that jumps by
characters up to the indexed character. It is a multi-byte character
wise function.

In case of correct run, it returns correct index to the next character
to inspect. In case of bug occurrence, __mbrtowc called from there
returns -2 (incomplete multi-byte character). Why? It seems to be caused
by remain_len being equal 1, even if there is still 6 bytes to inspect
("\267\357a\277\267\275").

I believe, that remain_len is computed incorrectly:

sed-4.2.1/lib/regex_internal.c:502 re_string_skip_chars()

      remain_len = pstr->len - rawbuf_idx;

pstr->len seems to be length of the remaining part of the string,
rawbuf_idx is the index of the remaining part of the string in the
original (raw) string.

I am not quite familiar with the code, but I believe that the expression
should be:
remain_len = pstr->raw_len - rawbuf_idx;


(略)

glibc ではこれか Bug 13637 – incorrect match in multi-byte (non-UTF8) string

なんか引っかかった覚えがあるようなバグなのであとで調べるか。

■_ 43秒で

How to create a Ruby extension in C in 43 seconds

How to create a Ruby extension in C in 43 seconds

By Peter Cooper / August 1, 2006

Two months ago, I wrote How to Create a Ruby Extension in C in under 5 minutes. But 
times have changed!

2012 update: Just tested and this all works in Ruby 1.9.3 almost six years later!

(略)

Copyright © 2006–2012 Peter Cooper

元々は2006年の記事かこれ。

■_ echo

echo って -- 特別視しないのだっけ?

echoで「-n」を出力する方法 | OKWave

echoで「-n」を出力する方法

echoで「-n」を出力するようにしたいのですが、
echo -nとすると「-n」がオプションと解釈されて何も表示されませんし、
echo -- -nとすると「-- -n」と表示されてしまいます。

echoで「-n」を表示させたい場合はどのように指定すれば良いのでしょうか?
(前後にスペースが入ってしまう、他のコマンドを使うなどはNG)

よろしくお願いいたします。

投稿日時 - 2012-03-01 15:01:32

■_

2012年03月01日

■_

出てすぐに買っていたのだけどろくに読んでいなかったこの本を読んでいたり。 「Driving Technical Change」に学ぶ、新しいツールや技術の導入戦略 - ITは芸術だ Driving Technical Change - 仄かに輝く

■_ Eiffel

結構好きだったりします >あいふぇる

Language Outline « Verifiable Software

Language Outline

In the course of this blog I am going to use a variant of Eiffel called “Modern Eiffel”.
This blog entry gives a short outline of the language elements. Although
“Modern Eiffel” is a full blown language with all sorts of imperative elements,
mutable reference type objects, multiple inheritance, dynamic bind etc. this blog entry
concentrates only on a small subset: immutable types and inductive types. The reason:
immutable/inductive types are a very important concept to verify statically the
correctness of a program. More advanced features will be introduced if necessary.

Skeleton of a class

Modern Eiffel is an object oriented language. All types are defined by classes (as in other
object oriented languages like C++, C#, java, scala, etc.). The skeleton of a class looks like

Moder Eiffel はオブジェクト指向言語です。すべての型は(C++やC#、Java、Scala等々といった
他のオブジェクト指向言語と同じように)クラスで定義されています。
クラスのスケルトンは次のような外見です


   class
      MY_CLASS   -- class name
   create
      creator1(a:A)  ...
      creator2  ...
   feature
      some_function(b:B): RT   ...

      some_command(c:C)  ...

      all(i:INT) some_property(i)
         proof
            ...
         end

      CHAR = CHARACTER   -- type alias
   invariant
      ...   -- consistency conditions
   end

Comments begin with “--” and span to the end of the line. Classes and types are always
written in uppercase. Each class can have creators by which objects of the corresponding
type can be constructed. The features of a class are either functions (i.e. routines which
return a value) or commands (i.e. routines which change the state of the object) or
assertions or type aliases.

コメントは “--" で始まり、行末まで続きます。
クラスと型は常に大文字で記述されます。
各クラスは対応する型のオブジェクトを構築できる creator を持つことが可能です。
クラスの機能は関数 (値を返すルーチン) もしくは
コマンド (オブジェクトの状態を変更するルーチン) であるか、
あるいは assertion か type aliases です。


Basic types

There are some basic types. These are types with built-in functions and built-in value
representation. The basic types are BOOLEAN, NAT (unsigned integers of a certain size),
INT (signed integers of a certain size). Beside their built-in functions and value
representation the basic types are nothing special. They are defined with classes as well.

いくつかの basic type があります。
それらは組み込み関数と組み込みの値表現 (value representation) を持った型です。
basic type には、BOOLEAN、NAT (特定の大きさの符号なし整数)、INT (特定の大きさの
符号つき整数) があります。組み込み関数と組み込みの値表現を除けば basic type は
特別なものではなく、クラスとしても定義されています。

   immutable class
      BOOLEAN
   feature
      implication alias "=>" (o:BOOLEAN): BOOLEAN
         external "built_in" end

      negated alias "not": BOOLEAN
         external "built_in" end

      conjuncted alias "and" (o:BOOLEAN): BOOLEAN
         external "built_in" end

      disjuncted alias "or" (o:BOOLEAN): BOOLEAN
         external "built_in" end

      ...
   end

Functions can have operator aliases for unary and binary operators. I.e.
having variables a,b,c of type BOOLEAN the expressions

関数は単項または二項の演算子としての operator alias を持つことが可能です。


   not a            -- highest precedence

   a and b

   a or b

   a => b           -- lowest precedence

have the expected meaning. The most important boolean operator is the implication “=>”.
It is right associative i.e. “a => b => c” is parsed as “a => (b => c)”. The
binary operators “and” and “or” are left associative. All binary boolean operators are
not strict (short circuited) i.e. the second operand is only evaluated if necessary to
determine the truth value of the expression.


これらの BOOLEAN 型の式は期待通りの意味を持っています。
このうち最も重要な演算子は “=>” です。
この演算子は右結合をするので “a => b => c” は “a => (b => c)” と
解釈されます。二項演算子の “and”と “or” は左結合です。
すべての二項 boolean 演算子は strict ではありません(短絡評価をします)。
つまり、それら演算子の第二オペランドは式の値を決定するのにそれが必要であるときに
のみ評価されるのです。

Default inheritance and equality

A class can inherit features from other classes. For this blog entry inheritance is not
important. I just mention the fact that each class has some implicit inheritance. A class T
with no inheritance clause is treated as if it were defined as

あるクラスは別のクラスから機能を受け継ぐことができます。
この blog では継承は重要ではありませんので、
単にそれぞれのクラスがいくつかの implict inheritance を持っていることにだけ言及します。
inheritance clause を持たないクラス T は次のように定義されたかのように扱われます。

   class
      T
   inherit
      -> ANY
      COMPARABLE
   ...
   end

The symbol “->” stands for conforming inheritance. For the following the class ANY is
not important. But the parent class COMPARABLE defines equality. It has the outline

   class
      COMPARABLE
   feature
      is_equal(o:like Current): BOOLEAN
         external "built_in"
         ensure
            all(x:like Current) x=x
            all(x,y: like Current) x=y => y=x
            all(x,y,z: like Current) x=y => y=z => x=z
            -- "=" has higher precedence than "=>"
         end
   end

The feature “is_equal” is used in Modern Eiffel to define equality. It is a built-in
function which guarantees properties which are expected from an equivalence relation.
Reflexivity (every entity is equal to itself), symmetry and transitivity. In Modern
Eiffel the postconditions of built-in routines are treated as axioms, i.e. properties
which do not need any proof. Note the transitivity law written as

この機能 "is_equal" は Modern Eiffel が equality を定義するのに使います。
これはまた等値関係や Reflexivity、smmetry、transitivity を expect する property
をもたらす組み込み関数です。
Modern Eifffel では組み込みルーチンの postconditions (事後条件?) は axioms として
扱われます。


  x=y => y=z => x=z

Usually one would expect the transitivity law written as

   x=y and y=z => x=z

Both forms are equivalent. This will be proved later. If possible we write all properties
with the implication operator, because implication is more powerful and practical for
proofs.

両方の形式は等価です。あとで説明することですが、
可能である場合にはすべてのプロパティは implication operator でもって記述します。
これは implication がより強力なものであり、practical for proofs であるからです。

Each class inheriting from COMPARABLE can redefine (i.e. overwrite) the feature “is_equal”.
The postconditions are inherited but in case of redefinition they are no longer treated as
axioms; they have to be proved to be true.

COMPARABLE から継承したクラスはその "is_equal" を再定義(上書き)することが可能です。
postcpnditions は継承されますが、再定義した場合にはもはや axioms としてみなされなくなります。
このため、


(略)

■_ VS 2011

βが公開されましたよ。と。

Visual Studio 11 Beta released : programming

VS really needs a checkbox that says "Don't ever install any piece of any version 
of SQL Server on my machine"

I also want a checkbox for "Seriously - don't touch my c:\ drive"


I gave up on that and just created a hard link from "c:\program files" to my 
D drive. (My C:\ drive is solid state)

VS 2010 was one of the things that more or less ignored the location settings in the 
installer for half the subcomponents

Edit- this apparently wasn't a "hard" link but whatever windows supports for 
symbolic links

Visual Studio and Office are the two worst offenders. I also think (at least for a 
while) if you installed Office first, then Visual Studio wouldn't even allow you to 
put it anywhere except C.

Which is annoying with "small SDD c:\ drive + large HDD d:\ drive" is now 
standard on any machine I build

If you can't install at least Windows and your apps on your SSD, and leave the HDD for 
data and games, then your SSD is too small. Solved.

Windows XP is 11 years old, and soon to be 3 versions back. When XP launched, that was 
the equivalent of Windows 95, or even WFWG if you don't count Me.

Unfortunately that simply doesn't matter - as long as users have XP computers you 
either have to compile for XP or it won't run on their system. And that's right now, 
depending on your sources, around 20%-50% of all desktop systems worldwide. Microsoft 
puts programmers in a stupid position with that. No new VS, no better c++11 support or 
ignoring half your customers. Microsoft probably has enough money to simply ignore 
over 20% of the market - most companies can't. Sorry, but just too early - Microsoft 
knows those numbers and the reasons for this are obviously not technical, but about 
forcing more people to buy newer Windows systems. That reason is fine for them, but it 
just sucks now for programmers worldwide.

Look on the bright side, round here we're still developing stuff in VB6.

■_ End of Life

InfoQ なんですぐに訳されますよね

InfoQ: Ruby Enterprise Edition End-of-Life, Phusion Focuses on Passenger

Phusion, the company behind Phusion Passenger, announced that their Ruby Enterprise Edition
(REE) is nearing its end-of-life. REE is based on MRI Ruby 1.8.7, which is also being
phased out (1.8.7 will receive regular maintenance until June 2012, and security fixes
until June 2013).

(略)

■_ 第六版

日本語訳はどうなるんだろう

Petzold Book Blog - “Programming Windows” 6ᵗʰ Edition

February 29, 2012
New York, N.Y.

Yes, it's true! Later this year — but perhaps sooner than you think — Microsoft Press 
will be publishing the long-awaited 6th edition of one of the bestselling computer 
programming books of all time, Programming Windows. Considering that the 5th edition 
was published towards the end of the last century, it's been a long time coming!

It's no coincidence that this announcement coincides with Microsoft's release of the 
Windows 8 Consumer Preview. The 6th edition of Programming Windows will focus on 
writing Windows 8 "Metro-style" applications using the C# programming 
language and XAML.

(略)

初版からどう変わっていったのか順に追いかけてみたい気もする。

■_


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

ホームへ


リンクはご自由にどうぞ

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