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

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

一つ前へ 2010年11月(下旬)
一つ後へ 2010年12月(中旬)

ホームへ

2010年12月09日

■_

なんでこんなに時間が足りない感が強いのだろう…

■_

ruby-core は斜め読みもいいところなのですが、印象に残ったので。

[ruby-core:33637] [Ruby 1.9-Bug#4135][Open] bug in calculations in 1.9.3dev / 1.9.2
Bug #4135: bug in calculations in 1.9.3dev / 1.9.2
http://redmine.ruby-lang.org/issues/show/4135

Author: Dmitrii Samoilov
Status: Open, Priority: High
Category: core, Target version: 1.9.x
ruby -v: ruby 1.9.3dev (2010-12-08 trunk 30125) [i686-linux]

$ ruby -v
ruby 1.9.3dev (2010-12-08 trunk 30125) [i686-linux]

I just installed ruby-head from rvm and run this in irb:

$ irb
ruby-head > 125.33 - (125.33/100.0*50.0)
 => 62.66499999999999
ruby-head > 125.33 / 100.0 * 50.0
 => 62.665000000000006
ruby-head > 15.33 / 100.0 * 50.0
 => 7.664999999999999
ruby-head > (15.33 / 100.0) * 50.0
 => 7.664999999999999
ruby-head > (14.33 / 100.0) * 50.0
 => 7.165000000000001

Which is obviously wrong.

The same in old ruby 1.9.2.dev

$ ruby -v
ruby 1.9.2dev (2009-07-18 trunk 24186) [i686-linux]
$ irb
ruby-1.9.2-preview1 > (14.33 / 100.0) * 50.0
 => 7.165000000000001

Ruby 1.8.7 looks good
$ ruby -v
ruby 1.8.7 (2010-04-19 patchlevel 253) [i686-linux], MBARI 0x8770, Ruby Enterprise Edition 2010.02

$ irb
irb(main):001:0> (14.33 / 100.0) * 50.0
=> 7.165

  
Issue #4135 has been updated by Yui NARUSE.

Learn floating point numbers.

What Every Computer Scientist Should Know About Floating-Point Arithmetic
http://docs.sun.com/source/806-3568/ncg_goldberg.html
http://wiki.github.com/rdp/ruby_tutorials_core/ruby-talk-faq#floats_imprecise
http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
----------------------------------------
http://redmine.ruby-lang.org/issues/show/4135

  
Issue #4135 has been updated by Dmitrii Samoilov.

Stupid me. Sorry guys.

  

■_ 昇格

すでに9日目のもあがってますが8日目から。


Day 8 – Different Names of Different Things « Perl 6 Advent Calendar

(略)

As pairs with already-seen keys get pushed onto the %inverse hash, the original value 
isn’t overriden but instead "promoted" to an array. Here’s a small 
demonstration:

    my %h;
    %h.push('foo' => 1);    # foo => 1
    %h.push('foo' => 2);    # foo => [1, 2]
    %h.push('foo' => 3);    # foo => [1, 2, 3]

All three (flip/reverse/invert) coerce their arguments to the expected type (if possible).
For example if you pass a list to flip, it is coerced into a string and then the string is
rever^W flipped.


へー。ありがたいといえばありがたい。のか?

■_


Learning Ruby - best advice/tips? : ruby

Hello /r/ruby::

I've decided to begin learning Ruby and I have programmed before in other languages 
(C++, Java, PHP, Python -- for school mostly). However, I'm not proficient in any of 
them. I'd like to change that with Ruby. I've skimmed a couple of books and even the 
looked a some sample Ruby code and am really amazed at how simple a lot of things are 
done with the language. So, I've got some questions.

1) I need some help from anyone who is proficient or has at least been programming in 
   Ruby for a while to give me some advice. So far, in this subreddit, people have 
   suggested some good Ruby books to begin with, such as:

    * Why's (Poignant) Guide to Ruby -- Didn't know what to think of this one, but it 
      did have great information, I'll probably go back and read it.

    * Learn to Program -- This one I bought and have read the first couple of chapters 
      -- I like it.

    * Ruby Pick Axe (though it's more of a reference)

So, it looks like books are covered for now at least.

2) What are some good beginner Ruby programming projects I can work on to become more 
   proficient with the language and also more involved with the Ruby community?

3) I'd like to design a very simple site/blog for personal use -- and if possible would
   like to use/test MySQL and Ajax, to get a better understanding of how Ruby works with
   these two other languages. I've worked with MySQL and PHP before, so I'm familiar 
   with MySQL; but haven't done anything with Ajax. Also, is there a Ruby web app that 
   can interface with MySQL -- much like PhpMyAdmin?

4) VIM. All of the code I've ever written has been done using VIM (IMO = best editor ever).
   What are the best plugins for Ruby? How do I go about setting up VIM to make it a solid
   Ruby editor/IDE?

5) Any other ideas/tips/advice? If so, do share.

Thanks everyone! Hopefully I can contribute to the Ruby community in the upcoming months.

これに対する反応は見てのお楽しみ。

■_

■_ yacc

でかるちゃ

強引に話を振ったにも関わらず、 shiro さんから返事をいただきました。 ありがとうございます。 挙げられたこの本 (The UNIX Programming Environment) ですが、 日本語版は例によって絶版状態ですね。いい本なのに(ってちと古いか)。 んで、この本では hoc (higher order caluclator) という電卓プログラムを yacc を使って実装しさらにそれを拡張して制御構造を関数定義を持った言語にまで仕立てる という章があります。 で、一番最初は

%{
  #define YYSTYPE double
%}
%token NUMBER
%left '+' '-'
%left '*' '/'
%left '%'
%left UNARYMINUS UNARYPLUS /* tanko- minus eg -2 .. */
%%
list:      /* nothing */
| list '\n'
| list expr '\n' {printf("\t%.8g\n",$2);}
;

expr: NUMBER {$$=$1;}
| '-' expr %prec UNARYMINUS {$$=-$2;}
| '+' expr %prec UNARYPLUS {$$=$2;}
| expr '+' expr {$$=$1+$3;}
| expr '-' expr {$$=$1-$3;}
| expr '*' expr {$$=$1*$3;}
| expr '/' expr {$$=$1/$3;}
| expr '%' expr {$$=(int)$1-(int)$3*((int)$1/(int)$3);}
| '(' expr ')'  {$$=$2;}
;

%% /* end of grammer*/

#include<stdio.h>
#include<ctype.h>
void warning(char *,char *);
char *progname;
int lineno=1;
main(int argc,char *argv[])
{
  progname=argv[0];
  yyparse();
}

int yylex()
{
  int c;
  while((c=getchar())==' ' || c=='\t')
    ;
  if(c==EOF)
    return 0;
  if(c=='.' || isdigit(c)){
    ungetc(c,stdin);
    scanf("%lf",&yylval);    /* lf -> long float -> double */
    return NUMBER;
  }
  if(c=='\n')
    lineno++;
  return c;
}

yyerror(char *s)
{
  warning(s,(char *) 0);
}

void warning(char *s,char *t)
{
  fprintf(stderr,"%s: %s",progname,s);
  if(t)
    fprintf(stderr,"%s",t);
  fprintf(stderr," near line %d\n",lineno);
}

こんな感じ。 誰かさんもこの辺から始めればよかったのに。 と /dev/null 送りのつぶやき。

Amazon.co.jp: UNIXプログラミング環境 (海外ブックス): Brian W.Kernighan, Rob Pike, 石田 晴久: 本

2010年12月08日

■_

今日、神田(神保町)の三省堂に行ってきたのですが、 書籍を店頭で印刷・製本「三省堂書店オンデマンド」12月15日スタート - ITmedia News ←これのスペースが用意されてなんかやってましたね(仕切りで中はうかがえず)。

書籍を店頭で印刷・製本「三省堂書店オンデマンド」12月15日スタート - ITmedia News

 第1弾として、和書2000タイトル(多巻物含め5000点以上)、洋書300万点超(学術書中心)を
提供。講談社やディスカヴァー・トウェンティワンなど国内各出版社が協力しており、和書ライ
ンアップはさらに充実させていく。具体的なタイトルは、開始日以降に案内する。

気になる。

そいや、オライリーの卓上カレンダー、オライリーの通販で買うしか手にいれる方法ないのかな。 紀伊國屋書店あたりでももらえたような気がしたんだけど、 日曜日に行ったときはメモパッドだったw んで、書泉グランデと三省堂も同様と。

■_ こんな本がほしい



Perl Books I Want - Modern Perl Books, a Modern Perl Blog
With Modern Perl available (ePub version coming soon) and my attention back on Using 
Perl 6, it's time to plan for the next wave of Perl books. Here's what I want:

    * Modern Perl and the CPAN. The title needs work, but think of it as the successor
      to Modern Perl. Where I didn't cover all of the great CPAN modules that real
      programs written by great Perl 5 programmers use all the time, this book has room
      for them.

    * Modern Perl OO with Moose. I've reached for where this book should be on my shelf
      far too often lately. You know you want this too. I have just the authors in mind
      too.

    * DBIx::Class. It's time.

    * Modern Perl Web Development with Plack. This book could be short, very short, 
      but no less useful for its size. It almost writes itself, given a good outline.

    * wxPerl, because I've never made sense of the C++ documentation.

    * Game Programming with SDL and Perl. Here's a long shot, but Kartik and company 
      have done far more with SDL_Perl than I ever have, making multimedia development
      far more convenient and far prettier than ever before.

    * Building Little Languages on Parrot with NQP, because NQP needs documentation 
      and Parrot's world domination plan requires it.

I have ISBNs at the ready and contracts to send. I believe I have audiences. (Please 
confirm!) Now I need authors.

That's my list. What's yours?

■_ 解読


F#:どう書く?org - 逆転したビット列 - Gushwell's F# Programming Diary
re: F#:どう書く?org - 逆転したビット列

let doukaku61 n =

   if n > 32 then invalidArg "n" "32 を超えています。"

   let n = int64 n

   let ( ** ) (x:int64) (y:int64) = (float x) ** (float y) |> int64

   seq { for x in 0L .. 2L**n-1L ->

           (x, n-1L)

           |> Seq.unfold (function

                | x, -1L -> None

                | x, i   -> Some ((x&&&1L) * 2L**i, (x>>>1, i-1L)))

           |> Seq.sum }

ううむ。わかるようなわからないような。

■_

■_

手が進まねえ…

■_ Perl 6 Advent Calendar

Day 7: Lexical variables « Perl 6 Advent Calendar

Programming is tough going. Well, stringing together lines of code isn’t that 
difficult, and prototyping an idea can be pleasant and easy. But as the size of the 
program scales up, and the maintenance time lengthens, things tend to get tricky. 
Eventually, if we’re unlucky, we’re overcome by the complexity — not necessarily the 
complexity of the problem we started out solving, but the complexity of the program 
itself. We get gray hairs from debugging, or we’re simply at a loss for how to extend 
the program to do what we want.

(以下略)
Day 8 – Different Names of Different Things « Perl 6 Advent Calendar

Newcomers to the Perl programming language, version 5, often complain that

they can't reverse strings. There's a built-in reverse function, but it doesn't 
seem to work at first glance:

    $ perl -E "say reverse 'hello'"
    hello

(以下略)

結構興味深い話題が続くなあ。

2010年12月07日

■_

宿題が~終わらない~♪

■_ めた

Perl 6 で入ってきた「メタ演算子」のお話。


Day 6: The X and Z metaoperators « Perl 6 Advent Calendar

Day 6: The X and Z metaoperators

By Matthew Walton

One of the new ideas in Perl 6 is the metaoperator, an operator which combines with an 
ordinary operator in order to change its behaviour. There are several of them, but in 
this post we will concentrate on just two of them: X and Z.

Perl 6における新しいアイデアのひとつにメタ演算子があります。
これは通常の演算子の振る舞いを変えるためにそれと組みあわせて使う演算子です。
メタ演算子にはいくつかありますが、ここでは X と Z に絞って説明します。

The X operator is one you might already have seen in its ordinary role as the infix 
cross operator. It combines lists together, one element from each, in every 
combination:

X 演算子は infix cross operator (中置のクロス演算子?) としてすでに見たことが
あるかもしれません。
これは要素ひとつひとつ同士を組み合わせるかたちでリストを組み合わせます

> say ((1, 2) X ('a', 'b')).perl
((1, "a"), (1, "b"), (2, "a"), (2, "b"))

However, this infix:<X> operator is actually just a shorthand for the X 
metaoperator applied to the list concatenation operator infix:<,>. Indeed, you're 
perfectly at liberty to write

しかし、この infix:<X> 演算子はリスト結合演算子  infix:<,>. に
対して X メタ演算子を適用した形の短縮形になっています。

> say ((1, 2) X, (10, 11)).perl
((1, 10), (1, 11), (2, 10), (2, 11))

If you like. So what happens if you apply X to a different infix operator? How about 
infix:<+>


> say ((1, 2) X+ (10, 11)).perl
(11, 12, 12, 13)

What's it done? Instead of creating a list of all the elements picked for each 
combination, the operator applies the addition infix to them, and the result is not a 
list but a single number, the sum of all the elements in that combination.

これで何が行われたのでしょうか?
すべての要素ごとに組み合わせたリストを生成するのではなくて、
要素をすべて加算するために適用されています。そしてその結果は
リストではなくひとつの数値、組あわせによって求まったすべての要素の和です。

This works for any infix operator you care to use. How about string concatenation, 
infix:<~>?

文字列の結合演算子 infix:<~> ではどうでしょうか?

> say ((1, 2) X~ (10, 11)).perl
("110", "111", "210", "211")

Or perhaps the numeric equality operator infix:<==>?
数値の等価演算子 nfix:<==> では?

> say ((1, 2) X== (1, 1)).perl
(Bool::True, Bool::True, Bool::False, Bool::False)

But this post is also meant to be about the Z metaoperator. We expect you may have 
already figured out what it does, if you've encountered the infix:<Z> operator 
before, which is of course just a shortcut for Z,. If a Haskell programmer understands 
infix:<Z> as being like the zip function, then the Z metaoperator is like 
zipWith.

Haskellプログラマーが infix:<Z> を zip 関数のようなものだと理解していれb
Z メタ演算子は zipWith のようなものだと理解できるでしょう。

このポストでは Z メタ演算子にも触れます。

> say ((1, 2) Z, (3, 4)).perl
((1, 3), (2, 4))
> say ((1, 2) Z+ (3, 4)).perl
(4, 6)
> say ((1, 2) Z== (1, 1)).perl
(Bool::True, Bool::False)

Z, then, operates on each element of each list in turn, working on the first elements 
together, then the second, then the third for however many there are. It stops when it 
reaches the end of a list regardless of which side that list is on.

Z is also lazy, so you can apply it to two infinite lists and it will only generate as 
many results as you need. X can only handle an infinite list on the left, otherwise it 
would never manage to get anywhere at all.

Z は lazy であるので、二つの無限リストに対して適用することが可能で、
そこから必要なだけの結果を生成するといったことができます。
X はその左辺に置かれたひとつに対してのみ無限リストを扱うことが可能で、
さもなければなんの結果も得られないでしょう。

At the time of writing, Rakudo appears to suffer from a bug where infix:<Z> and 
infix:<Z,> are not identical: the former produces a flattened result list. S03 
shows that the behaviour of the latter is correct.

These metaoperators, then, become powerful tools for performing operations 
encompassing the individual elements of multiple lists, whether those elements are 
associated in some way based on their indexes as with Z, or whether you just want to 
examine all possible combinations with X.

Got a list of keys and values and you want to make a hash? Easy!
キーと値のリストがあって、そこからハッシュを作りたい? それは簡単!

my %hash = @keys Z=> @values;

Or perhaps you want to iterate over two lists in parallel?
あるいは二つのリストを並行してイテレートしたいかも?

for @a Z @b -> $a, $b { ... }

Or three?
リストが三つなら?

for @a Z @b Z @c -> $a, $b, $c { ... }

Or maybe you want to find out all the possible totals you could get from rolling three 
ten-sided dice:

はたまた十面サイコロ三つを振ったときに出る可能性のある合計すべてを
見つけ出したいこともあるかもしれません:

my @d10 = 1 ... 10;my @scores = (@d10 X+ @d10) X+ @d10;

If you want to see some real-world use of these metaoperators, Sudoku.pm in Moritz 
Lenz's Sudoku solver.

■_ Python を学ぶべき?

reddit


Should I learn Python? : ruby

Yes, I'm in the right subreddit.

Any rubyists use python over ruby in some contexts? If so, which ones and why? Apart 
from winning by dying with the most skills, is it a useful addition?


Python has some good math libraries (see another post in this subreddit), that's about 
the only thing I can think of.


I agree, python often has better libraries for math/science type stuff. The NLTK is 
great for natural language processing.

Learning something new will keep your mind nimble, I say do it.

Source: I am someone who knows ruby and python


Seems at this point there's a lot more GTK apps written in python too. Sometimes a 
library you want to use leaves you no choice.

In all honesty, every time I use python I curse. I love simple things in ruby like 
String.length and Array.length, and am always frustrated when some functions sit in 
the root namespace like len()


Yes, it is a very useful tool. Not a perfect language, but a well evolved one. Lots of 
good quality libraries, excelent documentation, etc etc. It also covers a lot of stuff 
outside of the web development world (these days Ruby is pretty web-centric).

I have to say that if I had the choice I would use Python for most of the tasks on 
which I use Ruby, but I don't have that choice for now (I work for a mostly 
Ruby-centric company). Anyway, this is a matter or preference but if you don't try 
both you will never know which one fits you better. Also, knowing more stuff is better, 
expand your horizons :)

source: I use Ruby daily at my job but sometimes I use Python. On previous jobs I used 
Python full time (I have worked with both languages for 3+ years each and know them 
well)


You might find this interesting:

Python vs. Ruby: A Battle to The Death

The talk is actually targeted at people interested in ruby who already know Python, 
but he does a pretty cool comparison of the two languages which might help you anyway.

■_

もー斜め読みが精一杯 ○| ̄|_

Ada? Surely you jest Mr. Pythonman | unethical blogger
Ada? Surely you jest Mr. Pythonman
December 6, 2010 - 7:00am | by R. Tyler Croy

The past couple weeks I've been spending my BART commutes learning the Ada programming 
language. Prior to starting to research Ada, I sat in my office frustrated with Python 
for my free time hackery. Don't get me wrong, I love the Python language, I have 
enjoyed the ease of use, dynamic model, rapid prototyping and expressiveness of the 
Python language, I just fall into slumps occasionally where some of Python's 
"quirks" utterly infuriating.

以下略

Ada 好きなんだよなあ。割と。使ったことないけど :)

Efficient substring searching ? Phusion Corporate Blog

Efficient substring searching

By Hongli Lai on December 6th, 2010

There are many times when programmers need to search for a substring, for example when 
parsing text. This is commonly referred to as searching for a needle (substring) in a 
haystack (the string to search in). The most straightforward way to do this is by 
using search functions that your language provides:

   * C: strchr()/memchr(), strstr()/memmem()
   * C++: string::find()
   * Ruby: String#index or regular expressions
   * Python: string.find() or regular expressions
As useful as a COBOL programmer | The Joke Shop
“That sounds terrific,” said Jack. “But I’m curious. Why is everybody so interested in me?”

“Well,” said the spokesman. “The year 10000 is just around the corner, and it says 
in your files that you know COBOL”.

以下略

↑これはちょっとクスリときました。 reddit でも http://www.reddit.com/r/programming/comments/eglh0/the_cobol_programmer/

research!rsc: Yacc is Not Dead

Reports of yacc's death, at least in this case, are greatly exaggerated. The paper 
starts by arguing against the “cargo cult parsing” of putting together parsers by 
copying and pasting regular expressions from other sources until they work. 
Unfortunately, the paper ends up being an example of a much worse kind of cargo cult: 
claiming a theoretical grounding without having any real theoretical basis. That's a 
pretty strong criticism, but I think it's an important one, because the paper is 
repeating the same mistakes that led to widespread exponential time regular expression 
matching. I'm going to spend the rest of this post explaining what I mean. But to do 
so, we must first review some history.

以下略

「Yacc is dead」に対する反論とか。

■_ iconv

2010年12月06日

■_

・東スポ
コラムで面白いものを発見。

  電子書籍では味わえぬ袋とじの快感

つい最近、わが東スポ編集局にも、時代の最先端を行く「iPad」を持つモノが現れた。
編集局全体が、まるでモノリスに群がるサルの群れ(by2001年宇宙の旅)のような興奮に
包まれたのは言うまでもない。
  (略)
たとえアンドロイドが電気羊の夢を見る時代が到来したとしても、男の本能を刺激する
聖域「袋とじ」だけは紙のメディアでしか味わえない気がする
  

クラークにディックとw

来た来た Amazon.co.jp: プログラミング原論: アレクサンダー ステパノフ, ポール マクジョーンズ, Alexander Stepanov, Paul McJones, 柴田 芳樹: 本

価格: 	¥ 3,570
# 単行本(ソフトカバー): 285ページ
# 出版社: ピアソン桐原 (2010/12/24)
# ISBN-10: 4864010080
# ISBN-13: 978-4864010085
# 発売日: 2010/12/24
  
Twitter / @HATATANI Shinta: STLで有名なAlex Stepanovの書いたEl ...

STLで有名なAlex Stepanovの書いたElements of Programmingの邦題が「プログラミング原論」
に決まったらしいけど,ダイクストラの古典とかぶってて検索しにくい.http://j.mp/gbQm3x 
http://j.mp/ig0AXY

確かに。

■_ Why are variables "i" and "j" used for counters? (Stack Overflow)

大好物のネタが飛び込んできました :)

今回は非常にウケたネタ回答があります。


Why are variables "i" and "j" used for counters? - Stack Overflow

なぜ “i”や“j”という変数がカウンターに使われるのでしょうか?

I know this might seem like an absolutely silly question to ask, yet I am too curious 
not to ask...

Why did "i" and "j" become THE variables to use as counters in 
most control structures?

Although common sense tells me they are just like X, which is used for representing 
unknown values, I can't help to think that there must be a reason why everyone gets 
taught the same way over and over again.

Is it because it is actually recommended for best practices, or a convention, or does 
it have some obscure reason behind it?

Just in case, I know I can give them whatever name I want and that variables names are 
not relevant.

i=iteration while j=after interation – ajreal

strange 'c' was not choosen? as in the Intel 'cx' counter register. – snmcdonald

Is this the only SO question with no single-digit-scoring answers? – BoltClock

Cartesian coordinates – Nick D

@Bolt: not anymore – Carlos
It comes ultimately from mathematics: the summation notation traditionally uses i for 
the first index, j for the second, and so on. Example (from http://en.wikipedia.org/wiki/Summation ):

    \sum_{i=1}^{n} i = \frac{n^2 + n}{2}

It's also used that way for collections of things, like if you have a bunch of 
variables x1, x2, ... xn, then an arbitrary one will be known as xi.

As for why it's that way, I imagine SLaks is correct and it's because I is the first 
letter in Index.

@SLott: And why is i used in math? – SLaks

@Slaks: That's a good question. I actually think that "i" might come from 
integer more than index. I also think it's easy to write on a chalkboard. Back in the 
70's we were cautioned to be sure that we wrote our "i" and "j" in 
a perfectly distinctive manner. Indeed, we were told to draw our "i" exactly 
like a backwards "j" to be perfectly clear about it. – S.Lott

@S.Lott: I doubt it comes from integer. We use ℤ (blackboard bold Z) for the integers 
because it stands for the German word Zahlen, which means numbers. Assuming that the 
summation notation arose at around the same time, the German-based notation would be 
expected—and the German word for index is Index, which also begins with an i. And I 
can't think of many letters which are particularly hard to write on a chalkboard. Well, 
except ξ :-) – Antal S-Z

"This convention exists because this convention has existed before." That's 
kind of how etymology works: nobody knows why a particular noise had a particular 
meaning in PIE. It would be nice to explain the mathematical convention, but the 
question is "why are they used as counters in control structures", so until 
someone produces an answer that goes back further, this is the best. It does at least 
speculate why it's used in mathematics. A proper mathematical historian could find out, 
maybe using a binary chop. Euclid didn't use it, I bet von Neumann did. How about 
Cauchy? He used indexes a lot – Steve Jessop

I think it was Lagrange who recommended using a,b,c for constants of a function, and 
x,y,z for variables of a function. i,j,k denote the 'directions' of a vector, and the 
factors of a formal sum like this can be construed as degrees of freedom [directions, 
by another name] of the equation. – David 15 hours ago

I believe it dates back to Fortran. Variables starting with I through Q were integer 
by default, the others were real. This meant that I was the first integer variable, 
and J the second, etc., so they fell towards use in loops.


I think this comes from the way mathematicians seem to like to use i, j, k as handy 
subscripts for summation and matrix multiplication indices and what-not. I remember 
reading in an early Fortran II manual something about that. (Yes, Fortran II.) – 
S.Lott Nov 9 at 19:51

Yes, FORTRAN originates these conventions. – Xepoch Nov 10 at 0:26

Called implicit declaration... – Xepoch Nov 10 at 4:20

I was taught I through N not Q. Google seems to mostly agree. (different versions of 
FORTRAN?) – Hugh Allen Nov 12 at 14:14

i stands for Index.
j comes after i.


no, n comes after i - i n d e x. – Pete Kirkham Nov 9 at 20:18

I think he was talking about alphabet, try to use some imagination :) – Jack Nov 9 at 21:16


@Jack: I think @Pete was joking ;-) – Cpfohl Nov 9 at 21:59

@Cpfohl: yep, just wanted to be boring :D – Jack Nov 9 at 22:02

@Pete Kirkham: Thank you very much Pete, it was the best laugh I had in the past month. 
– AMissico Nov 17 at 18:21

Because of the name D*ijk*stra.


What, you're taking this question seriously? – bmargulies Nov 15 at 20:00

"LoL" would be my comment if it wasn't for the minimum characters limit ;) – 
naugtur Nov 16 at 12:21

That explanation might work better if his name wasn't really "Dÿkstra". – 
Jerry Coffin Nov 19 at 4:48

@Jerry, the name is Dijkstra with a ligature for ij, not Dÿkstra with trema on a y. – 
AProgrammer 17 hours ago


These symbols were used as matrix indexes in mathematics long before electronic 
computers were invented.


There's a preference in maths for using consecutive letters in the alphabet for 
"anonymous" variables used in a similar way. Hence, not just "i, j, 
k", but also "f, g, h", "p, q, r", "x, y, z" 
(rarely with "u, v, w" prepended), and "α, β, γ".

Now "f, g, h" and "x, y, z" are not used freely: the former is for 
functions, the latter for dimensions. "p, q, r" are also often used for 
functions.

Then there are other constraints on available sequences: "l" and 
"o" are avoided, because they look too much like "1" and 
"0" in many fonts. "t" is often used for time, "d &\1 
δ" for differentials, and "a, s, m, v" for the physical measures of 
acceleration, displacement, mass, and velocity. That leaves not so many gaps of three 
consecutive letters without unwanted associations in mathematics for indices.

Then, as several others have noticed, conventions from mathematics had a strong 
influence on early programming conventions, and "α, β, γ" weren't available 
in many early character sets.

Agreed. Although, a, b, c is a fairly commonly used sequence despite a having multiple 
meanings... – Stobor Nov 17 at 5:25
by discarding (a little biased)

a seems an array
b seems another array 
c seems a language name
d seems another language name
e seems exception
f looks bad in combination with "for" (for f, a pickup?)
g seems g force
h seems height

i seems an index                    
j seems i (another index)

k seems a constant k
l seems a number one (1) 
m seems a matrix
n seems a node
o seems an output
p sounds like a pointer
q seems a queue
r seems a return value
s seems a string
t looks like time
u reserved for UVW mapping or electic phase 
v reserved for UVW mapping or electic phase or a vector
w reserved for UVW mapping or electic phase or a weight
x seems an axis (or an unknown variable)
y seems an axis
z seems a third axis


Many possible main reasons, I guess:

    * mathematicians use i and j for Natural Numbers in formulas (the ones that use 
      Complex Numbers rarely, at least), so this carried over to programming

    * from C, i hints to int. And if you need another int then i2 is just way too long, 
      so you decide to use j.

    * there are languages where the first letter decides the type, and i is then an 
      integer.

i = iota, j = jot; both small changes.

iota is the smallest letter in the greek alphabet; in the English language it's 
meaning is linked to small changes, as in "not one iota" (from a phrase in 
the New Testament: "until heaven and earth pass away, not an iota, not a dot, 
will pass from the Law" (Mt 5:18)).

A counter represents a small change in a value.

And from iota comes jot (iot), which is also a synonym for a small change.

cf. http://en.wikipedia.org/wiki/Iota

i is for index and integer, and was in use in mathematics for sum/sigma notation long 
before COBOL and FORTRAN were invented. The next is j, k, l - in alphabetical order. 
Greek does not come into it.

It is that simple: Why does this question have a bounty?

Well from Mathematics: (for latin letters)

a,b: used as constants or as integers for a rational number
c: a constant
d: derivative
e: Euler's number
f,g,h: functions
i,j,k: are indexes (also unit vectors and the quaternions)
l: generally not used. looks like 1
m,n: are rows and columns of matrices or as integers for rational numbers
o: also not used (unless you're in little o notation)
p,q: often used as primes
r: sometimes a spatial change of variable other times related to prime numbers
s,t: spatial and temporal variables or s is used as a change of variable for t
u,v,w: change of variable
x,y,z: variables

It's interesting that so many people point to summation formulas in math. Certainly i 
and j are common, but I would say n is as common as i (and m as j if using n instead 
of i). This makes me think the fortan answer is also onto something. Some earlier 
programmers chose the i,j,k over n,m,l and now it's just convention in programming. 
Seems sticker than summation conventions in math or physics.

It definitely comes from mathematics, which long preceded computer programming.

So, where did if come from in math? My completely uneducated guess is that it's as one 
fellow said, mathematicians like to use alphabetic clusters for similar things -- f, g, 
h for functions; x, y, z for numeric variables; p, q, r for logical variables; u, v, w 
for other sets of variables, especially in calculus; a, b, c for a lot of things. i, j, 
k comes in handy for iterative variables, and that about exhausts the possibilities. 
Why not m, n? Well, they are used for integers, but more often the end points of 
iterations rather than the iterative variables themselves.

Someone should ask a historian of mathematics.

■_

reddit 編。


Why are variables “i” and “j” used for counters? : programming

Because of the name Dijkstra.

I want to believe this. So I will.


If I ever need to write a loop four levels deep I will be using "s" as the 
next counter variable for sure.


The first SO response seems like the obvious answer to me.

The Fortran creators borrowed it from mathematicians, and ever since we've been coding 
in the shadow of the TRAN.


I'm annoyed by the fact that the first brings up a very obvious follow-up question 
("Why is i used as an iterator in mathematics?") and doesn't answer it. :/

Yes, I don't see why it's the "chosen" answer.

The standard work for the history of mathematical notations is still Florian Cajori's 
A History of Mathematical Notations. If we look there, he notes that Euler introduced 
the idea of Σ, but no one really used it until much later on apart from Lagrange. 
However, if we look at the articles cited, they don't use Σ in the same way we do - 
only with it being very closely related to infinitesimals.

Keep on reading, and he says that S was used for sum by others, but Fourier started 
using Σ in Théorie Analytique de la chaleur. Indeed, we can find this online, and he 
uses both S and Σ, for different things. My French is a bit rusty, but it appears he 
uses S (without an explicit index variable - i is used implicitly) when he wants the 
index to range over the naturals - 1, 2, 3, 4... etc. Σ is used later on when he wants 
to sum over an infinite number of terms in a similar way to using ∫ (and, 
incidentally, he has no qualms writing Σ for i ranging from -1/0 to 1/0!).

It is obvious that the Σ notation is fairly new or would be unusual to most readers, 
because each time he uses it he explains it anew, rather than relying on one 
explanation. He also uses j toward the end of the document, but doesn't explain his 
choice of i or j any where. He also uses i as a matrix index, and it would seem that 
this is a more established notation.

So far, I conclude that it started with matrix notation and was used with Σ primarily 
because his sums are over matrices/vectors.

Unfortunately, A History of Mathematical Notations Volume II isn't freely available 
online, and this is where the stuff on matrices is.

Edit: just found a 'free' source.


What's your 'free' source? That book sounds like it'd be up my alley.


another interesting answer is the one about the Hamilton Quaternions

http://stackoverflow.com/questions/4137785/why-are-variables-i-and-j-used-for-counters/4359877#4359877


Taken from Hacker News, here is their discussion.
http://news.ycombinator.com/item?id=1971507

あとでてきとーに訳をつけていきます。たぶん。

■_ 実体


「憂鬱なプログラマのためのオブジェクト指向開発講座」はどうトンデモなのか - プログラミング言語を作る日記
p.362

    さて,それらを学習する前に-つ知っておかなければならないことがあります.これは「実体」です.

    C言語では,関数に変数を渡すときは,値渡しとポインタ渡しの2種類の方法がありました.C++で
    は,さらにもう一つの方法として,実体渡しという方法があります.

    実体渡しは,値渡しとポインタ渡しの中間のような方法です.

    まず、従来からある「値渡し」と,ここで学ぶ「実体渡し」の違いについて考えてみましょう.値渡し
    では,関数に渡されるのは,あくまでもその変数の「コピー」です.ですから,渡されたデータをい
    くら書き換えても,元のデータには全く影響がありません.しかし、実体渡しの場合はその「変数
    そのもの」,つまり実体が渡ります.これを書き換えたら,元データにはもちろん影響します.そ
    れは,元データそのものなのですから.
  
私の知る限りにおいて、「実体渡し」という言葉をこういう意味(つまり「参照渡し」の意味)で 使っている例は、この本と、この本の読書ノート的なWeb記事でしか見たことがありません。た いてい、「実体渡し」と言えば「値渡し」の方を意味するんじゃないでしょうか。 言っていることはわかります。私などは「ポインタじゃなくて実体を渡す」という意味で「実体 渡し」という言葉を使ってきたわけですが*5、「コピーじゃなくて実体を渡す」という意味で 「実体渡し」という言葉を使って悪いことはないでしょう(どうせきちんと定義された用語では ないので)。でも、あまり一般的な使い方とは思えません。私の周りだけかもしれませんが、Cプ ログラマにとって「ポインタじゃなくて実体」という言い回しはかなりされると思っていて、わ ざわざ混乱を招くような用語を使う意味はあるのでしょうか。

この「実体渡し」なる用語ですが、最近出版された はじめての「Go言語」 (I・O BOOKS) の中で出てきました。やはり call by reference の意味で使っていたと思います。

わたしとしては call by value、call by reference のどちらの言いかえとしても あまりいいものではないと感じます。 call by object でも通じそうな気がするし。

■_ まだかなまだかな~♪


推薦図書/必読書のためのスレッド 58 
70 デフォルトの名無しさん [] 2010/12/05(日) 12:22:32 ID: Be:
    Programming Principles and Practice Using C++
    Bjarne Stroustrup
    http://www.amazon.co.jp/dp/0321543726/

    これの日本語版が欲しい。出ないの? 

71 デフォルトの名無しさん [sage] 2010/12/05(日) 12:55:15 ID: Be:
    >>70
    翔泳社から出るらしいけどいつ出るかは不明 

75 デフォルトの名無しさん [sage] 2010/12/05(日) 17:35:00 ID: Be:
    >>70
    訳だか監訳だかしてる人が年内に出したいとどっかに書いていたが、その後の音沙汰はないな。
    まだ~(AA略 

ほんと、まだですかねー。って原書で読んじゃったけど。

■_

2010年12月05日

■_

・内川がホークスへ移籍するのが決まった途端、手のひらを返したように 「大した選手じゃない」的な発言が目立つようになったmixi某コミュを見て苦笑。

C++が使われないって憤ってる人は、 「Java から Ruby へ」みたいな本を出すとかしないといけないんじゃないかな。 とふと思った。C を dis ったりしても益はないんじゃないかな。

■_ メタプログラミングの会

あいかわらず竹迫さんのプレゼンは聞き惚れ(見惚れ?)てしまうほど上手だった。 普段から練習してたりするんだろうか。

感想も書かないとなあ。

■_ Help me learn Haskell, and I will pay it forward. : haskell

今朝方見かけたもの。


Help me learn Haskell, and I will pay it forward. : haskell

I am working my way through the book "Programming in Haskell" by Graham 
Hutton, along with the lectures on Channel 9 by Erik Meijer 
( http://www.cs.nott.ac.uk/~gmh/book.html ).

I would like for someone to "grade" or at least comment on my solutions to 
the problems in the book and in the lectures. I shouldn't need a lot of feedback, and 
no tutoring or explanations would be necessary, I can teach myself.

I have $0 though so the only way I can think of repaying whomever does this is to do 
the same for others.

Thanks. If you have ideas to an alternate solution to this problem please post it in 
the comments.

tldr: Grade my solutions to problems and I will try to do the same for others.


I'm happy to help and I'm pretty sure you can go onto the #haskell IRC channel any 
time and find someone to "grade" your solutions. The reason why Haskellers 
love helping newbies is that they fondly remember the time their own mind was blown.


Honestly this is absolutely my favorite part about Haskell. Even if I never use it for 
any "real" work I think I will always appreciate how many times my mind has 
been blown (even just this far) in learning it. Lisp is the only other language that 
has ever really done that to me at all, and it was much less frequent.

Also would you mind pm'ing me your email and I can send you what I have done? I guess 
I am a bit awkward about just going on #haskell, and posting my solution after 
solution, though I know that they are very helpful and it is one of the best channels 
I have ever been in.


Does this help? http://www.cs.nott.ac.uk/~gmh/solutions.pdf

It does, thank you. I guess for some of these though I might benefit from human 
feedback, or a pointer of where I went wrong or a critique of how what I wrote could 
be optimized. But thank you; I (stupidly) was unaware of that links existence.


Just put your source to GitHub and I'll comment there.

これに対するいけがみさんの反応。



Twitter / @Ikegami Daisuke: freenode #haskell のみなさんはとて ...
freenode #haskell のみなさんはとても親切です…英語じゃないとわかってもらえないけど

Twitter / @Ikegami Daisuke: 書いたソースを hpaste でさらして、こうすれば ...

書いたソースを hpaste でさらして、こうすればもっとよくね、みたいな反応をもらう:
  http://hpaste.org


Twitter / @Ikegami Daisuke: ぼっちでも HLint 先生が添削してくれるのがよい ...

ぼっちでも HLint 先生が添削してくれるのがよい感じ : http://hpaste.org

どんどん書いていかないとだめですよね○| ̄|_

■_


推薦図書/必読書のためのスレッド 60 [chaika]
1 デフォルトの名無しさん [sage] 2010/12/04(土) 01:42:39 ID: Be:
    前スレ
    推薦図書/必読書のためのスレッド 59
    http://hibari.2ch.net/test/read.cgi/tech/1288373503/ 

2 デフォルトの名無しさん [sage] 2010/12/04(土) 01:43:36 ID: Be:
    プログラム技術板倉庫 http://s225.web.fc2.com/index.html
    New Books http://f57.aaa.livedoor.jp/~newbooks/
    cBooks http://www.cbook24.com/
    2chBooks http://deztec.jp/x/04/06/2ch/
    推薦書籍集 http://bookshelves.at.infoseek.co.jp/
    プログラム技術板倉庫 http://tito.fc2web.com/2ch/tech/index.html
    Standard Books http://www.yfcbookshelf.com/authentic_books_frame.htm
    ITpro SkillUP BOOKS http://itpro.nikkeibp.co.jp/books/
    コンピュータ関連書籍新刊一覧 http://pc.watch.impress.co.jp/docs/2007/market/i_nbook.htm
    プログラミングの良書100冊! http://itpro.nikkeibp.co.jp/article/COLUMN/20060127/228096/?ST=skillup
    日経ソフトウエア2004年12月号特集「プログラミングの良書100冊!」 http://itpro.nikkeibp.co.jp/article/COLUMN/20060223/230481/
    日経 IT Pro 記者の眼 - 古くなっても名著は名著 http://itpro.nikkeibp.co.jp/free/ITPro/OPINION/20041026/151768/
    「プログラミングの良書100冊!」 分析/設計のエキスパートになるために http://itpro.nikkeibp.co.jp/article/COLUMN/20060210/229019/
    The Linux Reading List HOWTO http://www.linux.or.jp/JF/JFdocs/Reading-List-HOWTO.html 

22 デフォルトの名無しさん [sage] 2010/12/05(日) 06:00:24 ID: Be:
    もう少し早く言えば良かったと思うんだけど、>2とか直さないとね
    もう更新されてないのが混じっているから・・・

    で、新刊チェックに使えるホームページは無いかな?
    コンピューター関連書籍として、電気電子まで含んでいて欲しいのだけど、そう言うの無いんだよね
    amazonでジャンル絞るしかないのかな 


なかなかこれというのはないんですよねえ(あったら教えて)。 情報の量と質によっては有料でもいいんだけど。

■_ THINK

頭字語つくってる単語が面白いなあと。


Think, for Perl's sake - Perlbuzz

I'm no longer surprised when I read about verbal abuse of other humans in my community. 
It makes me sad, both for the person who would say that to someone else, and for the 
person who gets the abuse. Worse, it makes me sad that the abusers don't care about 
the effects on their fellow human beings, or on the projects that they are 
representing.


略

The other day I ran across an acronym, THINK, that gives questions to ask about what 
you're about to communicate, before you actually say it.

Is what I'm about to say:

    Thoughtful
    Honest
    Intelligent
    Necessary
    Kind 

Geeks in technical discussions are really good at the Intelligent, and usually 
Thoughtful. The Honest is just a given.

It's with Necessary and, especially, Kind where some fail, with damaging results.

I'd like to urge all of us to keep THINK in mind in all our interactions, whether in 
IRC, mailing lists or in person at user group meetings and conferences.

As an aside, I've always moderated Perlbuzz comments, and will continue to do so. 
THINK crystallizes my criteria perfectly. 

■_

■_

Google のあれで使われたプログラミング言語の傾向とか。


Google AI Challenge: Languages Used by the Best Programmers | (R news & tutorials)

The Google AI Challenge recently wrapped up with a Lisp developer from Hungary as the 
winner.  The competition challenges contestants to create bots that push the limits of 
AI and game theory.  These bots compete against one another, and a complete ranking of 
competitors is available.  The big story today is that the winner (Gábor Melis) used 
Lisp to beat out over 4000 other contestants around the world using a host of 
different programming languages.   

Google AI Challenge は最近、ハンガリーからの Lisp developer が勝者となって幕を
閉じました。この competition challeges contests は
(push the limits of AI and game theory な)ボットを作るというものでした。
これらのボットはほかのボットと compete し、competition の完全なランキングも
入手可能です。今日の big story は勝者である Gabor Melis が Lisp を使って
異なる言語を使う4000人を超える世界中のライバルたちに打ち勝ったということです。


Paul Graham has stated that Java was designed for "average" programmers 
while other languages (like Lisp) are for good programmers.  The fact that the winner 
of the competition wrote in Lisp seems to support this assertion.  Or should we see Mr. 
Melis as an anomaly who happened to use Lisp for this task?

Paul Graham は、(Lispのような) 他の言語が優れたプログラマー (good programmers) に
向けて作られているのに対し、Java は「平均的なプログラマー」(average programmers)
のために設計された言語であると主張しています。今回の competition の勝者が Lisp
を使っていた事実はこの主張を裏付けるもののように思われます。
Or should we see Mr. Melis as an anomaly who happened to use Lisp for this task?


Programming Languages Usage

Java, C++, Python and C# were heavily used overall.
全体的には Java、C++、Python、C#が多く使われている

     language count(*)

1        Java     1634
2         C++     1232
3      Python      948
4          C#      485
5         PHP       80
6        Ruby       55
7     Haskell       51
8        Perl       42
9        Lisp       33
10 Javascript       19
11          C       18
12      OCaml       12
13         Go        6
14      Scala        4
15     Groovy        1

In the Top 200
そのうち上位200名での内訳

     language count(*)
1        Java       70
2         C++       64
3      Python       34
4          C#       17
5           C        4
6     Haskell        3
7         PHP        3
8        Ruby        2
9  Javascript        1
10       Lisp        1
11      OCaml        1


Top 100
上位100名で

1     Java       33
2      C++       32
3   Python       20
4       C#        9
5        C        3
6  Haskell        1
7     Lisp        1
8    OCaml        1

Top 10
  language count(*)
1     Java        4
2      C++        3
3       C#        2
4     Lisp        1

■_

あとでよむ


  Category Theory for the Mathematically Impaired: An Outline of A Short Reading List for “Mathematically-impaired Computer Scientists Trying to Learn Category Theory” ≪ Monadically Speaking: Adventures in PLT Wonderland

While reading through this week’s Issue 160 ? December 1, 2010, of the “Haskell 
Weekly News,” by Daniel Santa Cruz, on the Haskell-Cafe mailing list, I came across 
the following interesting blog entry describing a reading list for
“mathematically-impaired computer scientists trying to learn category theory”:


2010年12月04日

■_

昨日は途中までまとめてたけど眠気に負けた。

メタプログラミングの会 : ATND に行ってきました。途中 ゲーデル、エッシャー、バッハ―あるいは不思議の環 20周年記念版 が読みたくなった(謎)。
メタプログラミングの会 - Onion開発しつつ、PEGEXを開発する日記 メタプログラミングって何だろう 帰って来たNemerle

■_ Father of British computing Sir Maurice Wilkes dies

三日くらい前についったーでちらっと見かけたのですが、 やっぱり事実だったのか。


BBC News - Father of British computing Sir Maurice Wilkes dies

The "father" of British computing, Sir Maurice Wilkes, has died at the age of 97.

Sir Maurice was the designer and creator of Edsac, a computer that ran its first 
program in May 1949.

The Cambridge machine was the first widely-useable stored program machine and was very 
influential on the nascent British computer industry.

It set standards for how computers should be used in academia and business that have 
lasted until the present day.


(略)

The success of Edsac caught the attention of catering firm J Lyons which funded 
further development of the machine and led to the creation of the Leo - one of the 
first machines put to dedicated business use.

Innovations at the Cambridge computer laboratory, such as microprogramming and 
time-sharing, were widely influential in the industry at large.

"If any person deserves the title of the father of British computing, it is 
surely Professor Sir Maurice Wilkes," said Prof Lavington.

この本も何度となく紹介しているけど、一度は読んでおくのをオススメ。
ウィルクス自伝―コンピュータのパイオニアの回想
ウィルクス自伝―コンピュータのパイオニアの回想

■_


ふらっとC#,C♯,C#(初心者用) Part66 
329 デフォルトの名無しさん [sage] 2010/12/04(土) 01:02:17 ID: Be:
    型変換がわけわかんね

    intのデータをbyte配列に入れるとかまたその逆とか
    stringのデータをbyte配列に入れるとかまたその逆とか

    C言語でいうところの

    memset(&data[100],0,size-100);

    的な100番地から後ろをクリアみたいなことしたいときにどうするだとか
    とにかく知恵と勇気でどうにもならない言語で困る

    なんか型変換(型解決?)一覧表みたいなのがほしいね
    どっかにない?
    なかったら俺がアフィ目的で作ってお金稼ぐけど 

330 デフォルトの名無しさん [sage] 2010/12/04(土) 01:13:49 ID: Be:
    >>329
    >intのデータをbyte配列に入れるとかまたその逆とか
    BitConverter.GetBytes/BitConverter.ToInt32
    >stringのデータをbyte配列に入れるとかまたその逆とか
    BitConverter.GetBytes/BitConverter.ToString
    指定されたエンコーディングのバイト配列が欲しいならEncoding.GetBytes/Encoding.GetString

    >memset(&data[100],0,size-100);
    そういうのは危険だからできないようになってる。
    unsafeなら可能だけど一括でクリアするような用途では誰も使わない。

    >なかったら俺が作る
    需要がない。古い考え方を捨てるとこから始めようか。 

331 デフォルトの名無しさん [sage] 2010/12/04(土) 01:14:45 ID: Be:
    >>329
    そんな中途半端な知識で作るとかマジ迷惑だから勘弁してくれ 

332 デフォルトの名無しさん [sage] 2010/12/04(土) 01:16:50 ID: Be:
    >>329
    それ、知恵と勇気じゃない。
    無知と無謀。

    エンディアンの違いとか、
    バイトアラインの違いとか、
    int のサイズの違いとか、
    色んなものに悩まされた結果、memset は使えないという英知にようやく到達したのに。 

333 デフォルトの名無しさん [sage] 2010/12/04(土) 01:37:22 ID: Be:
    知恵と勇気で勝ち残れ 

334 デフォルトの名無しさん [sage] 2010/12/04(土) 01:39:49 ID: Be:
    メダロットとはまた懐かしいネタを 

335 デフォルトの名無しさん [sage] 2010/12/04(土) 01:45:21 ID: Be:
    >>330
    いちいちそんなクラス知ってないといけないっつーのがなんかすげー嫌だよ

    >そういうのは危険だからできないようになってる。
    なんで?
    すげー使うのに
    かりにやりたいときはいちいち全部コピーしないといけないのか?
    ウンコー

    >需要がない
    あるよ
    絶対ある
    だって現にBitConverterとか長ったらしい名前のクラス知らないとこの操作できないだろこの言語 

336 デフォルトの名無しさん [sage] 2010/12/04(土) 01:46:42 ID: Be:
    > クラス知らないと
    そういってオレオレライブラリ作られる方が面倒って直ぐ分からないですかね 

337 デフォルトの名無しさん [sage] 2010/12/04(土) 01:47:32 ID: Be:
    BitConverterが明らかにC#使って書かれていないであろう事実にウケル 

338 デフォルトの名無しさん [sage] 2010/12/04(土) 01:55:13 ID: Be:
    >>335
    だったらC#じゃなくてC++/CLI使えばいいんじゃない?
    .netを利用しつつC言語の資源も使いまわせるわけだし 

339 デフォルトの名無しさん [sage] 2010/12/04(土) 01:56:40 ID: Be:
    C++/CLIとかきもすぎる
    使ってみて一時間でアンインスコしたわ。 

340 デフォルトの名無しさん [sage] 2010/12/04(土) 01:57:23 ID: Be:
    >>335
    20年くらい寝てたの? 

341 デフォルトの名無しさん [sage] 2010/12/04(土) 01:59:49 ID: Be:
    C#でBitConverterは作れないからな
    他にも作れないものありそう 

342 デフォルトの名無しさん [sage] 2010/12/04(土) 02:04:18 ID: Be:
    >>339
    もう自分で言語作れよ 

343 デフォルトの名無しさん [sage] 2010/12/04(土) 02:06:39 ID: Be:
    C--か 

344 デフォルトの名無しさん [sage] 2010/12/04(土) 02:08:07 ID: Be:
    いつもの荒らしが騒いでるんだろ。
    僕は馬鹿ですとアピールして何がしたいのやら? 

345 デフォルトの名無しさん [sage] 2010/12/04(土) 02:08:15 ID: Be:
    >>335
    >>332 

346 デフォルトの名無しさん [] 2010/12/04(土) 02:08:28 ID: Be:
    C#が不便なら他を使えばいいだけだ。
    1つの言語だけを使わなきゃいけないわけでもないし。

    BitConverterで済むこと程度なら、ちょっと調べりゃいいことだと思うけどな。 

347 デフォルトの名無しさん [sage] 2010/12/04(土) 02:09:13 ID: Be:
    >>341
    unsafe使えば作れるんじゃない? 

348 デフォルトの名無しさん [sage] 2010/12/04(土) 02:10:58 ID: Be:
    作れるね。 

349 デフォルトの名無しさん [sage] 2010/12/04(土) 02:12:31 ID: Be:
    >>329>>335
    第二のCOBOLer もはや老害。 

350 デフォルトの名無しさん [sage] 2010/12/04(土) 02:14:47 ID: Be:
    >>344
    あの子はCなんて使えないだろ 

351 デフォルトの名無しさん [sage] 2010/12/04(土) 02:19:06 ID: Be:
    >>350
    この子もC使えないと思う。
    まともなC使いならこの程度の問題で困るわけない。質問書く時間で検索してMSDN見て終わり。 

352 デフォルトの名無しさん [sage] 2010/12/04(土) 02:26:32 ID: Be:
    memset(&\1data[100],0,size-100); が使えて
    BitConverterが使えないってのも不思議な話ではあるな
    結局思い通りにコードが書けなくて愚痴りたいだけなんだろ
    まあそれで気が済むなら好きなだけ書きこんでいってくれ 

353 デフォルトの名無しさん [sage] 2010/12/04(土) 02:34:28 ID: Be:
    >100番地から後ろをクリアみたいなことしたいときにどうするだとか

    ライブラリじゃなくて基本文法だと思うが。
    for (var i = 100; i < ar.Length; i++) ar[i] = (byte)0;

    それか配列なんだからArrayクラス調べれば
    Array.Clear(ar, 100, ar.Length - 100);
    ぐらいすぐ見つかるだろ。 

354 デフォルトの名無しさん [sage] 2010/12/04(土) 02:35:35 ID: Be:
    アレィ見てたのね~ 

355 デフォルトの名無しさん [sage] 2010/12/04(土) 03:47:35 ID: Be:
    うむ 

■_

三日目のネタから。


Day 3 – File operations « Perl 6 Advent Calendar
(略)

Useful idioms

Creating a new file

        open('new', :w).close

"Anonymous" filehandle

        given open('foo', :w) {
            .say('Hello, world!');
            .close
        }

close を書かなくてすむというわけではないのか…

■_

2010年12月03日

■_

ねむい

■_ ちょっといいはなし

くだすれDelphi(超初心者用)その52 
366 デフォルトの名無しさん [sage] 2010/12/01(水) 00:27:11 ID: Be:
    お知恵を拝借 バイナリで見えるファイルを
    00 01 02 03 04 05 06 07~
    x1 x2 y1 y2 x3 x4 y3 y4~

    y1 y2 x1 x2 y3 y4 x3 x4~ という2個づつ連続して入れ替えたいです
    どう書けばいいでしょうか

    Delphi 5 が自分の行く研究室に入ってて書いてコンパイルの方法はわかります。
    友人のグループ課題で実験のとき計測器を逆につないでデータとっていたそうで
    いま必死になってバイナリエディタでちまちま殺気だってやってるようです

    データ名は 1.dat 2.dat と数字で連続しています百数個あるとか
    レポート提出間に合わない~手伝ってと泣かれてるのでおねがいします 

367 デフォルトの名無しさん [sage] 2010/12/01(水) 02:20:57 ID: Be:
    相談に乗ってたら間に合わなそうだから作ったぞ。

    ■コンパイル
    1. フォームを適当な大きさにして、ボタンも何も配置しない。
    2. これをすべてコピー、エディタに上書きで貼り付け。
    http://pastebin.com/cu8jviaN
    3. イベントの設定が1つだけ必要。オブジェクトインスペクタの「イベント」タブを開き、OnCreateのところにFormCreateを入力する。

    ■使い方
    書き換えたいファイル(複数可)をドラッグしフォームにドロップする。
    ファイルのあったフォルダに新しく「NewFiles」というサブフォルダが作られ、その中に書き換えたファイルが格納される。

    元ファイルは壊さないようにしてあるけど、念のため必ずバックアップしとけよ。 

368 デフォルトの名無しさん [sage] 2010/12/01(水) 14:11:25 ID: Be:
    >>367
    フォームダブルクリックでいいんじゃ・・・ 

369 デフォルトの名無しさん [sage] 2010/12/01(水) 16:23:52 ID: Be:
    >>367
    我慢できなくなって書きなおしてしまった
    http://pastebin.com/FERePZWu 

370 デフォルトの名無しさん [sage] 2010/12/01(水) 18:56:40 ID: Be:
    おい、改悪になってんぞw
    2バイト毎に書き込みとかファイルIO多すぎて遅いだろww
    1ファイルのサイズが分からないから全部メモリに置くのも確かに得策ではないけど、
    せめて0x1000バイト単位でバッファリングするとか色々あるだろ… 

371 デフォルトの名無しさん [sage] 2010/12/01(水) 19:02:00 ID: Be:
    そういうのってOSが勝手にやってくれるんじゃねーの? 

372 デフォルトの名無しさん [sage] 2010/12/01(水) 19:22:19 ID: Be:
    俺も書いてみた
    http://pastebin.com/DhwJmVD3

    >>371
    富豪的な考え方だな
    とりあえずFILE_FLAG_WRITE_THROUGHやFILE_FLAG_SEQUENTIAL_SCANの意味でも調べてみたら?
    それが理解できたらFileOpen関数の実装を見比べてみるとか 

373 366です [sage] 2010/12/02(木) 00:44:01 ID: Be:
    うおぉすごい 返事が遅れましてすみませんありがとうございます。
    2ちゃんにはファイアーウォールで帰宅まで書き込めませんでした
    友人とそのグループどうやら徹夜してたみたい。
    昼前に>>367さんのレスみて
    この話をメールしたら即答で飛びついてきました。

    Delphi 5 入りのパソコンはウィルス対策で外からのメディア付け禁止、インターネット回線ダメ
    つくったプログラムは研究室備えのメディア買ったら持ち出しOK
    な条件だったようで、
    インターネット繋がるところさがして携帯にソースコピーして
    小さい画面見ながらちまちまw入力しましたよ
    帰宅して預かったデータの1つで確認できました!

    >>369さんも>>372さんもありがとうございます。
    ソースプリントアウトして置かしてもらえるように頼めと言っておきます。
    電話の向こうで泣いてました
    ほんとうにありがとう 

374 367 [sage] 2010/12/02(木) 02:19:09 ID: Be:
    >>373
    そりゃ良かった。
    「並び替えの順番が違いました」とか言い出す可能性を考え単純な構成にしたけど、
    そんな事情ならソースをもっと短くなるよう工夫したほうが良かったかな。
    …しまった。誤ってフォルダをドロップした場合の対策を入れ忘れてた。反省。
    ちゃんとするなら42行目のbeginの次行に、if not FileExists(FileName) then Exit; を挿入せよ。

    >>368-369
    だいぶスッキリしたねー。
    でもやはり小刻みにReadやWriteを連続させるのは気になってね。実際に比べてみたことないけど。
    ダブルクリック指示しないのは間違いの発生を減らすためだよ。
    >>372
    やたら高度に発展してて、思わず吹いたよ。ここでアセンブラが出てくるとは(笑)
    美しいけど、目的を知ってないと一見しただけでは理解できないなあ。 

375 367 [sage] 2010/12/02(木) 02:29:36 ID: Be:
    >>373
    うへ。すまん、指示間違ってた。if not FileExists(PathFile) then Exit; な。
    自分のプログラムも読めない俺が居た。 

376 デフォルトの名無しさん [sage] 2010/12/02(木) 04:03:39 ID: Be:
    すごい上から目線でふいた 

377 デフォルトの名無しさん [sage] 2010/12/02(木) 04:15:07 ID: Be:
    ROL EAX,16 ってEAXレジスタの値を16ビット動かしてるわけか
    なるほど便利な命令があるんだなぁ

    アセンブラでやらないなら、and $FF00 とかでマスクしながら上位・下位を交換すればよさそう 

378 デフォルトの名無しさん [sage] 2010/12/02(木) 04:57:32 ID: Be:
    >>374
    単純な構成というなら>>372が一番単純な構成じゃないか?全然高度でも何でもないし。
    お前さん自身が言うように理解させることではなく、ともかく作ってしまうのが目的であれば、
    アセンブラ使おうが何だろうが問題ないし、並び替え方法が違う可能性に対しても
    その部分だけ関数として括りだしてる>>372の方がよっぽど柔軟にできてると思うな。

    >>377
    n := n and $FFFF0000 shr 16 or n and $FFFF shl 16;
    ってところか。これだと5命令なんだよな。ROLだけで済むのを知るとこれでも長く感じてしまう。 

379 367 [sage] 2010/12/02(木) 12:20:17 ID: Be:
    >>378
    高度ってのは学生さんのこと心配してるんじゃなくて、
    一見した瞬間には理解できなかった俺自身の感想だよ。
    俺も>>372のようなシンプルかつ高速な手法を発想できればいいが、、、ぜんぜん無理だ。 

380 デフォルトの名無しさん [sage] 2010/12/02(木) 13:32:51 ID: Be:
    こうやって何人かが色んな視点で書くきっかけを作った367が一番偉いよ 

ROL EAX,16 って単なるローテート命令のような…ってRISCだとなかったりするんだっけか。 しかしバイナリエディタで手作業はない(^^;

■_

いろいろ。

Schneier on Security: Software Monoculture
Software Monoculture

In 2003, a group of security experts -- myself included -- published a paper saying 
that 1) software monocultures are dangerous and 2) Microsoft, being the largest 
creator of monocultures out there, is the most dangerous. Marcus Ranum responded with 
an essay that basically said we were full of it. Now, eight years later, Marcus and I 
thought it would be interesting to revisit the debate.

You Must Learn JavaScript ? Article ? The Nerdary

If you asked me 3 years ago what language you should learn I would've said Ruby. If 
you asked me 6 years ago, it was PHP.

If you're going to learn a language now, you need to learn JavaScript.

もしあなたが今、ひとつ言語を学ぼうとしているのなら、JavaScirpt を学ぶ必要がある。

Why?
なぜか?

It's my belief that every single web programmer should learn JavaScript. There are 
many new technologies coming out that fuel this principle. There is one single reason 
behind it. It's ubiquitous. You can work for anyone and do amazing things if you're 
using JavaScript. You can do it instantly on any machine.

すべての single web programmer はJavaScirpt を学ぶべきであるというわたしの信念である。
この原則 (principle) を満たす多くの多くの新規テクノロジーが世にでた。
そこにはひとつの理由が隠されている。それは (JavaScirptが) どこにでもある。ということだ。
JavaScirpt が使えれば、すべての人のために、信じられないようなことができる。
すべてのマシンで即座に行えるのだ。

■_ Advent

いろいろありますが Perl 6 もご多分に漏れず。 Day 1 – Reaching the Stars « Perl 6 Advent Calendar Day 2 – Interacting with the command line with MAIN subs « Perl 6 Advent Calendar


Day 1 – Reaching the Stars « Perl 6 Advent Calendar

Day 1 – Reaching the Stars
By ttjjss

Coming from the Perl 5 world, or from some other background, you may think of the programming language and its implementation as the one thing, or at least things very strongly tied to each other. Perl 6 is different. The “official” part is the specification (the Synopses) and the tests suite. Perl 6 encourages multiple implementations. Any implementation passing the official test suite and fulfiling the Synopses may call itself “a Perl 6 implementation”. While there is still no such implementation, there is alredy a few compilers in the ecosystem.

Rakudo is targetting the Parrot virtual machine, and it's the most complete implementation so far. Niecza is targetting .NET and is aiming to study performance issues. There is also Yapsi, whose “author has claimed that it's official for over half a year now, and not once been contradicted” :) We will be using Rakudo for our examples as it is the most complete implementation around and has the largest ecosystem built around it.

Like with Perl 6, there is no “one Rakudo to rule them all”. The Rakudo development team has decided to keep the compiler separate from the distribution. That means the Rakudo release is not a ready-to-use Perl 6 tarball, with modules, documentation and a virtual machine. That's what Rakudo Star is. First released about half a year ago, Rakudo Star contains the toolbox with everything needed for Perl 6 hacking: a release of Parrot virtual machine, the Perl 6 Book, a bunch of modules and the Rakudo itself.

Getting Rakudo Star

The Rakudo Star tarballs are located at https://github.com/rakudo/star/downloads. Go get one suitable for your system and become ready for Christmas… again!

This entry was posted on December 1, 2010 at 2:04 pm and is filed under 2010. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. 
Day 2 ― Interacting with the command line with MAIN subs ≪ Perl 6 Advent Calendar
Day 2 ― Interacting with the command line with MAIN subs
By Moritz

In Unix environment, many scripts take arguments and options from the command line. With Perl 6 it's very easy to accept those:

2日目 コマンドラインとMAIN関数の交流 - 葡萄酒の雑記集 2.0(笑)

■_

zshがなくてrootでログインできなくなった | OKWave
Solarisの経験はある程度ありますが、Linuxは初心者です。
CentOS5.5をインストールして、passwdファイルを書き換え、デフォルトのシェルをzshにしました。

■_

2010年12月02日

■_

あれやらこれやら。

うっちーは結局ホークス行きか。

■_ きたきた

これでカレンダーももらおう


O'Reilly Japan - プログラマが知るべき97のこと

人々のさまざまな思いを技術で形にするプログラマ。本書は世界中で活躍するプログラマによる97本の
エッセイを収録した書籍です。プログラミングにおいてもっとも重要な事柄は何か、バージョン管理や
テスティング、設計原則とコーディングテクニック、また腕を磨くための勉強法などについて、経験豊
かなプログラマが自らの体験を踏まえて解説します。プログラマを勇気づけ、新たな気づきをもたらす
一冊です。日本語版では、小飼弾、関将俊、舘野祐一、まつもとゆきひろ、宮川達彦、森田創、
吉岡弘隆、和田卓人による10本の書下ろしを収録。

目次
監修者まえがき
はじめに

    01	分別のある行動
        セブ・ローズ(Seb Rose)
    02	関数型プログラミングを学ぶことの重要性
        エドワード・ガーソン(Edward Garson)
(略)
    91	良いプログラマになるには
        ピート・グッドリフ(Pete Goodliffe)
    92	顧客の言葉はそのまま受け取らない
        ネイト・ジャクソン(Nate Jackson)
    93	エラーを無視するな
        ピート・グッドリフ(Pete Goodliffe)
    94	リンカは魔法のプログラムではない
        ウォルター・ブライト(Walter Bright)
    95	ペアプログラミングと「フロー」
        グドニー・ハウクネス(Gudny Hauknes)、カリ・ロスランド(Kari Rossland)、
        アン・カトリン・ガナット(Ann Katrin Gagnat)
    96	テストは正確に、具体的に
        ケブリン・ヘニー(Kevlin Henney)
    97	ステートに注目する
        ニクラス・ニルソン(Niclas Nilsson)

日本人プログラマによる知っておくべき10のこと

    01	命を吹き込む魔法
        森田 創
    02	ロールプレイングゲーム
        関 将俊
    03	ルーチンワークをフローのきっかけに
        宮川 達彦
    04	プログラマが持つべき3つのスキル
        吉岡 弘隆
    05	快適な環境を追求する
        舘野 祐一
    06	見知らぬ人ともうまくやるには
        小飼 弾
    07	不具合にテストを書いて立ち向かう
        和田 卓人
    08	育ちのよいコード
        森田 創
    09	Noといえることの大事さ
        宮川 達彦
    10	名前重要
        まつもと ゆきひろ

寄稿者紹介

■_


Postfix Notation Mini-Lecture

Postfix Notation
Mini-Lecture

Bob Brown
Information Technology Department
School of Computing and Software Engineering
Southern Polytechnic State University

Copyright © 2001, 2005 by Bob Brown

Every student of computer science should understand the concept of postfix notation 
and the use of stacks. For students of computer architecture this postfix notation 
mini-lecture is really an aside to show you how mind-bogglingly useful the concept of 
a stack is. It doesn't make any difference whether the stack is implemented in 
hardware and supported by the microarchitecture or simulated using an array and 
totally a creation of the high-level language programmer.

コンピューター科学のすべての学生は後置記法のコンセプトを理解すべきであり
また、スタックの使用を理解しておくべきである。コンピューターアーキテクチャ
の学生たちにとって、この後置記法の mini-lecture は


At some point in your career you will be asked to write a program that can interpret 
an expression in a notation similar to that of algebra. Getting something like 
(A+B)/(C-D) right can seem like a daunting task, especially when you are asked to 
write code that will interpret any valid expression. It turns out to be surprisingly 
easy if the program is decomposed into two steps: translation to postfix notation and 
evaluation of the postfix notation expression. This is not a new idea... it was 
described by Donald Knuth in 1962 and he was writing a history!

 
Evaluating Postfix Notation
後置記法の評価


Evaluating an expression in postfix notation is trivially easy if you use a stack. The 
postfix expression to be evaluated is scanned from left to right. Variables or 
constants are pushed onto the stack. When an operator is encountered, the indicated 
action is performed using the top elements of the stack, and the result replaces the 
operands on the stack.

後置記法の評価は、スタックを使えばとても簡単にできます。
後置記法の式を評価するにはその式を左から右へとスキャンします。
変数や定数はスタックへとプッシュします。
演算子に遭遇したときには、実行されるアクションはスタックにある要素を使って行われ、
その結果でスタックのオペランドを置き換えます。

Let's do an example using the postfix expression AB+CD-/. In order to see what's going 
on as the expression is evaluated, we will substitute numbers for the variables. The 
expression to be evaluated becomes 9 7 + 5 3 - /. This is equivalent to (9 + 7) / (5 - 3)
so we expect the answer to be eight.

You will see the expression scanned from left to right. A yellow highlight shows the 
term currently being scanned. The digits in the expression are pushed onto the stack 
and the operators are performed.

Experiment with the animation until you are sure you understand what's going on.

Now that you see how easy it is to evaluate an expression that's in RPN form, you will 
want to convert ordinary infix expressions to RPN so that you can evaluate them. That 
turns out to be easy, too, if you use a stack.
 

We know that the infix expression (A+B)/(C-D) is equivalent to the postfix expression 
AB+CD-/. Let's convert the former to the latter.

わたしたちは (A+B)/(C-D) という中置式がAB+CD-/という後置式と等価であることを
理解しています。では前者を後者へと変換してみましょう。

We have to know the rules of operator precedence in order to convert infix to postfix. 
The operations + and - have the same precedence. Multiplication and division, which we 
will represent as * and / also have equal precedence, but both have higher precedence 
than + and -. These are the same rules you learned in high school.

わたしたちは中置式を後置式に変換するためには演算子優先順位の規則を知っておかなければなりません。
+ と - という演算子は同じ優先順位を持っています。
わたしたちが * と / でそれぞれ表す乗算と除算も等しい優先順位です。
しかしこれら二つは + と - よりも高い優先順位を持っています。
これはあなたが高校で学んだであろう規則と同じものです。


We place a "terminating symbol" after the infix expression to serve as a 
marker that we have reached the end of the expression. We also push this symbol onto 
the stack.

わたしたちは中置式のあとに、式の終端に到達したことを表すマーカーの役割を果たす
“終端記号”を置きます。この記号はスタックにもプッシュします。

After that, the expression is processed according to the following rules:
このようにしてから、以下に挙げた規則に従って式が処理されます:

    * Variables (in this case letters) are copied to the output
      変数はそのまま出力にコピーする

    * Left parentheses are always pushed onto the stack
      左カッコは常にスタックへ積む

    * When a right parenthesis is encountered, the symbol at the top of the stack is popped
      off the stack and copied to the output. Repeat until the symbol at the top of the stack
      is a left parenthesis. When that occurs, both parentheses are discarded.

      右カッコに遭遇したときには、スタックトップにあるシンボルをポップして取り出し
      出力へコピーする。これをスタックトップのシンボルが左カッコになるまで繰り返す。
      左カッコに出会ったら、右カッコと一緒に捨てる。

    * Otherwise, if the symbol being scanned has a higher precedence than the symbol at the
      top of the stack, the symbol being scanned is pushed onto the stack and the scan pointer
      is advanced.
      それ以外の場合、スキャンしたシンボルがスタックトップにあるシンボルよりも高い優先順位
      を持っていればスキャンしたシンボルをスタックに積み、スキャンポインターを進める。

    * If the precedence of the symbol being scanned is lower than or equal to the precedence of
      the symbol at the top of the stack, one element of the stack is popped to the output; the
      scan pointer is not advanced. Instead, the symbol being scanned will be compared with the
      new top element on the stack.
      スキャンしたシンボルがスタックトップにあるシンボルよりも低い優先順位のものであれば
      スタックからシンボルをひとつポップして出力し、このときスキャンポインターは進めない。
      そしてスキャンしたシンボルを新しいスタックトップにあるシンボルと比較する。

    * When the terminating symbol is reached on the input scan, the stack is popped to the output
      until the terminating symbol is also reached on the stack. Then the algorithm terminates.

      入力のスキャンが終了記号に到達したならば、同様に終了記号が現れるまでスタックを
      ポップし、出力を行うことを繰り返す。スタックが空になれば手順終了。

    * If the top of the stack is a left parenthesis and the terminating symbol is scanned, or a
      right parenthesis is scanned when the terminating symbol is at the top of the stack, the
      parentheses of the original expression were unbalanced and an unrecoverable error has
      occurred.

      スタックトップにあるのが左カッコでスキャンしてきたのが終了記号である場合、もしくは
      スタックトップに終了記号があるときにスキャンしてきたものが右カッコである場合には
      元の式にあったカッコ対はバランスの取れたものではなく、回復不能なエラーが
      発生している。


When an infix expression has been converted to postfix, the variables are in the same 
order. However, the operators have been reordered so that they are executed in order 
of precedence.

中置式が後置式に変換されたとき、その変数は元の式と同じ順序になっています。
演算子は、優先順位にしたがって実行するために並べ替えられています。

Understanding Table 5-21 in Tanenbaum

The rules expressed as a list in the previous section are shown in a nice, unambiguous 
table in Structured Computer Organization by Andrew Tanenbaum (1999). Unfortunately, 
for some students the "train" analogy used by Tanenbaum gets in the way of 
seeing how to use this table. Here is the material on pp. 339-340 of Tanenbaum 
presented in terms of a stack rather than with the train analogy. The "scan 
pointer" is a way of keeping track of which token in the input expression is 
being examined. It is analogous to the yellow highlight in the animation.

    * The terminating symbol is appended to the expression to be converted and also 
      pushed onto the stack.

      変換を行うために終端記号が式に追加され、スタックにも終端記号が積まれる。

    * The scan pointer is set to the leftmost symbol of the input expression. Scanning 
      proceeds left-to-right.
      スキャンポインターが入力式の最も左にあるシンボルの位置にセットされる。
      スキャンは左から右へ向かって行われる。

    * If a variable is encountered, it is copied to the output and the scan pointer is 
      advanced.

    * If an operator symbol is encountered, it is compared with the symbol at the stop 
      of the stack using Table 5-21, and one of the following actions is taken depending
      on the number from the table:

         1. The symbol being scanned is pushed onto the stack and the scan pointer is 
            advanced.

         2. The stack is popped and the symbol from the stack is copied to the output. 
            The scan pointer is not advanced.

         3. The symbol at the top of the stack is deleted and the scan pointer is 
            advanced. (This is how parentheses are removed from the infix expression.)

         4. Done. The expression has been converted and the algorithm terminates 
            successfully.

         5. Error. The parentheses in the original expression were not balanced, and 
            the expression cannot be converted.

    * After each action is taken, a new comparison is made between the symbol being 
      scanned, which may be the same as in the previous comparison, and the symbol at
      the top of the stack. This continues until the algorithm terminates.


http://www.spsu.edu/cs/faculty/bbrown/web_lectures/postfix/table-5-21.gif


Figure 5-21 from Tanenbaum (1999).

Find the symbol at the top of the stack on the left and the symbol being scanned 
across the top. The action to take is indicated by the number at the intersection of 
the row and column.

Cite this paper as:

Brown, B., (2001). Postfix Notation Mini-Lecture. Retrieved on 2010/11/30 from:
http://www.spsu.edu/cs/faculty/bbrown/web_lectures/postfix/.

Please take a moment to provide comments on this Mini-Lecture.

References

Knuth, Donald E. (1962), "A History of Writing Compilers," Computers and Automation,, December, 1962, reprinted in Pollock, Barry W., ed. Compiler Techniques, Auerbach Publishers, 1972.

Tanenbaum, Andrew S. (1999), Structured Computer Organization, Prentice-Hall.

Further Reading

You can find a short birgraphical article about Łukasiewicz in the Wikipedia and 
another biographical article at the University of St. Andrews. These links will open 
new windows.

Back to the Web Lectures Table of Contents

Back to Brown's home page.

Last updated: 2009-08-21 13:07


Printed on 2010-Nov-30 20:31 from http://www.spsu.edu/cs/faculty/bbrown/web_lectures/postfix/

じかんがねーーーっ。 ってまあ、四則演算くらいの評価は結構簡単にできるのですよ。はい。

■_

よくある? 質問。


How to pass member function to a function pointer? - Stack Overflow

How to pass member function to a function pointer?
関数ポインターにメンバー関数を渡すにはどうすれば?

class Child;
class Parent
{
public:
  void (*funcPointer)();
  void (*funcPointer2)(Parent* _this);
  void (Child::*funcPointer3)();
};

class Child: public Parent
{
public:
  void TestFunc(){

  }
  void Do(){
    Parent p;
    p.funcPointer=TestFunc; //error  
    p.funcPointer2=TestFunc; //error too.
    p.funcPointer3=TestFunc; //this works
    p.funcPointer3=&>Child::TestFunc // this works too.
    p.funcPointer3();    // error,term does not evaluate to a function, how to call?
  }
};

err:cannot convert from 'void (__thiscall Child::*)(void)' to 'void (__cdecl *)(void)'

thanks for all!

You can't. You either pass a pointer to a static method or Parent has to accept also a 
pointer to the object.

You might want to look at boost::bind and boost::function for that:

#include <boost/bind.hpp>
#include <boost/function.hpp>
struct Y
{
    void say(void) { std::cout << "hallo!";}

    boost::function<void()> getFunc() { return boost::bind(&>Y::say, this); }
};

struct X
{
    //non-boost:
    void (Y::*func)();
    Y* objectY;
    void callFunc() { (objectY->*func)(); }

    //boost version:
    boost::function<void()> f;

};


X x;
Y y;
x.f = boost::bind(&>Y::say, boost::ref(y));
x.f = y.getFunc();
x.f();
x.func = &>Y::say;
x.objectY = &y; 
x.callFunc();

You can't. From the C++ FAQ #33.2:

    [33.2] How do I pass a pointer-to-member-function to a signal handler, X event 
    callback, system call that starts a thread/task, etc?

    Don't.

    Because a member function is meaningless without an object to invoke it on, you can't
    do this directly (if The X Window System was rewritten in C++, it would probably pass
    references to objects around, not just pointers to functions; naturally the objects
    would embody the required function and probably a whole lot more).

It then goes on to talk about workarounds involving global variables (blech) and 
non-member functions.


In response to your last edit, to form a pointer-to-member, you have to use &> 
and classkey::. There's no equivalent to the function name to pointer-to-function 
implicit conversion for normal functions.

// not valid:
p.funcPointer3=TestFunc;

// valid:
p.funcPointer3 = &Child::TestFunc;

To access a member through a pointer-to-member you have to use either the .* or ->* 
operator.

E.g.

(this->*p.funcPointer3)();

■_

2010年12月01日

■_

・ムダヅモ
ページ数少ない?

class Fixnum
 def reverse(n)
   (0..n-1).inject(0){|acc, x| acc*2 + self[x] }
 end
end

n=4
p (0..2**n-1).map{|e| e.reverse(n) }

桁数(ビット数)はどう扱ったものやら。

しかしなぜこれを題材にしたんだろうか パチンコ・ナポレオン、年明... - 写真共有サイト「フォト蔵」

■_ CSVで

RFCの、データフィールドにおけるキャラクターがASCIIの範囲って制限はどうにかならんのだろうか。


CSV file with japanese characters not opening properly in Excel 2007 - Stack Overflow


Hi,

I have a simple JSP to download a csv file containing Japanese characters. Downloaded 
file opens correctly in notepad++ and shows right characters but when I try to open 
same file in Excel 2007, It shows some different characters, probably in some other 
encoding.

My JSP looks like this.

<%@ page language="java" contentType="text/csv; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.io.*"%>
<%  
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/csv; charset=UTF-8");
    response.addHeader("Content-Disposition", "attachment; filename= " + "Test.csv");
    OutputStream output = response.getOutputStream();   
    System.out.println("Chaaracter encoding : " + response.getCharacterEncoding()); 
    Writer writer = new BufferedWriter(new OutputStreamWriter(output,"UTF-8"));

    String japanese = "注目のキーワード";   
    InputStream in = new ByteArrayInputStream(japanese.getBytes("UTF-8"));
    BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));                  
    String line = null;                 
    while ((line = reader.readLine()) != null) {
        writer.write(line);
        writer.write(System.getProperty("line.separator"));
    }           
    reader.close(); 
    writer.flush();
    writer.close();
%>

This string in Excel 2007 looks like this : 注目ã®ã‚­ãƒ¼ãƒ¯ãƒ¼ãƒ‰

Could any one please help me here. User should be able to directly open file in Excel 
when he clicks on download link(above jsp).

Any help would be appreciated.

Thanks Jitendra

I have already answered similar question. Please read here: setting a UTF-8 in java 
and csv file. Generally the problem can be solved by putting "magic" code 
(know as Byte Order Mark) in the beginning of the file.


Please call it "Byte Order Mark" :) It's no magic.

You are right. It was magic for me cause I did not know what is this. 


hey thanks all. It is working now. – Jitendra 19 hours ago

BOM かあ…

■_ 質の悪いコード (Bad code) は


Bad code isn't Technical Debt, it's an unhedged Call Option | Steve Freeman

Bad code isn't Technical Debt, it's an unhedged Call Option
#質の悪いコードは技術的負債というものではなく、ヘッジされていない Call Option である
#金融関係の用語らしいですがよくわかりません → Call Option

Written on 23 Jul 2010

I'd been meaning to write this up for a while, and now Nat Pryce has written up the 
140 character version.

Payoff from writing a call.

This is all Chris Matts' idea. He realised that the problem with the “Technical Debt” 
metaphor is that for managers debt can be a good thing. Executives can be required to 
take on more debt because it makes the finances work better, it might even be 
encouraged by tax breaks. This is not the same debt as your personal credit card. 
Chris came up with a better metaphor, the Call Option.

I “write” a Call Option when I sell someone the right, but not the obligation, to 
buy in the future an agreed quantity of something at an price that is fixed now. So, 
for a payment now, I agree to sell you 10,000 chocolate santas1 at 56 pence each, at 
any time up to 10th December. You're prepared to pay the premium because you want to 
know that you'll have santas in your stores at a price you can sell.

略

コメントがたくさんついていますが略。

■_ yacc は死んだ

そこかしこで話題になってますが


[1010.5023] Yacc is dead
http://arxiv.org/abs/1010.5023


Yacc is dead | Lambda the Ultimate
http://lambda-the-ultimate.org/node/4148


Yacc is dead? Implementations in Scala and Haskell. Anyone play with this yet? : haskell
http://www.reddit.com/r/haskell/comments/eczfc/yacc_is_dead_implementations_in_scala_and_haskell/


[1010.5023] Yacc is dead
Yacc is dead
Authors: Matthew Might, David Darais
(Submitted on 24 Oct 2010)

Abstract:

We present two novel approaches to parsing context-free languages. The first approach 
is based on an extension of Brzozowski's derivative from regular expressions to 
context-free grammars. The second approach is based on a generalization of the 
derivative to parser combinators. The payoff of these techniques is a small (less than 
250 lines of code), easy-to-implement parsing library capable of parsing arbitrary 
context-free grammars into lazy parse forests. Implementations for both Scala and 
Haskell are provided. Preliminary experiments with S-Expressions parsed millions of 
tokens per second, which suggests this technique is efficient enough for use in practice. 

わたしたちは文脈自由言語を解析するための二つの新しいアプローチを提供する。
一つ目のアプローチは Bzrowski の derivative from regular expression
to context-free grammars の 拡張を基としたのである
二つ目のアプローチはパーザーコンビネーターの derivative (派生)の
一般化に基づくものである。これらの技法の payoff は小さく(250行以下のコード)、
文脈自由文法を lazy parse forests へと解析する能力を持った parsing library の
実装が容易にできるということである。Scala と Haskell に対する実装が行われている。
S式を使った Prekiminary experiments では一秒あたり数百万のトークンを解析した。
これはこの技法が実用には十分な効率であることを suggest している。

derivative from regular expression ってどんなのだろう…

■_ 今日の丸投げ

情報Bとか期末考査ってことは高校生?


至急!情報BでPHPのプログラミングを習っています。明日が期末考査で、それぞれの... - Yahoo!知恵袋

至急!情報BでPHPのプログラミングを習っています。明日が期末考査で、それぞれの意味みたい
なものを説明できなくてはいけません。

そこでそれぞれプログラミングの一文を書くので、以下のものの意味を教えて下さい。

echo"You are a student.";と
echo'You are a student.';において
'"←これらの違い
echoの意味

if(a=='Tom'){$b='is';}で
ifを使う意味
==←これの意味

for($i=1;$i<1001;$i++){で
forを使う意味
++の意味

<form action="mondai1.php"method="POST">で
form actionの意味
methodの意味
POSTの意味

<input type="hidden"name="flag value="1">の
input typeの意味
hiddenの意味
flag valueの意味

<input type="text"name="in_1">の
textの意味
in_1の意味

<input type="submit">の
submitの意味

$a=$_POST["in_1"];の
この文自体の意味

$flag=$_POST["flag"];の
この文自体の意味



また
二重ループとは何のためにするのか。
選択ソートと交換ソートの違い

も教えて下さい!!


よろしくお願いします!!



①クオート内で変数、エスケープ文字が使用できるか使用できないか。

②条件分岐をしたい時。==は左辺と右辺が同等であることをi示す。

③ループしたい時。++はインクリメント

④actionは端直に言えば処理させたいページに飛ばす。methodはPOST, GETの事を指す。アドレ
スで反映されるかされないかで見分けるのが基本的。

⑤typeはテキストなのかパスワードなのか、隠しフィールドなのかを設定できる。flagはパラメ
ータ名。valueはパラメータにくっつく値

⑥上記と同じ

⑦submitは送信させるボタンのこと。(HTML上では。)

⑧$aに$_POST["in_1"]の値を代入する。

⑨上と同じ

⑩例えばだけど、2次元配列の処理をしたい時に使う。

⑪選択ソート:http://ja.wikipedia.org/wiki/%E9%81%B8%E6%8A%9E%E3%82%BD%E3%83%BC%E...
交換ソート(例:バブルソート):http://ja.wikipedia.org/wiki/%E3%83%90%E3%83%96%E3%83%AB%E3%82%BD%E...

最後に

あなたなんの為に学校に行って勉強してるんですか?

PHP とか使うのねえ。

■_

もういっこ学生さんネタ。


Things I See In Student Code | FOB

Things I See In Student Code
学生のコードにわたしが見たもの

I've read quite a lot of student code over the years. Some of it is quite good. A lot 
of it is full of predictable badnesses. These notes attempt to enumerate some of this 
badness, so that you may avoid it.

This is pretty C-centric in its current form. However, many of its lessons are 
multilingual. This is a living document, so don't expect it to be the same next time 
you look at it. In particular, the numbering may change if something gets inserted in 
the middle. It is revisioned automatically by Drupal, so feel free to point at a 
particular revision if you care.

   1. Lacks Author Name and/or Copyright Notice
      作者名や著作権表示がない

      If a license applies, make sure that's there too.

   2. Doesn't Pass '-Wall'
      '-Wall' をパスしない

      Until you're very old and very wise, just treat warnings as errors. By then, 
      you'll know enough to keep doing it.

   3. Broken Indentation
      壊れたインデント

      Just don't go there. I'm serious. Your code work products should never contain 
      an ASCII tab character; get your editor to help you.

   4. Copy-and-Paste Errors
      コピペの間違い

      Sometimes we copy and paste. This is often a bad idea; a unit or macro abstraction
      would have been better. If it's infeasible (as it is, rarely) to go there, at least
      proofread the living daylights out of your copy-pasted code, and then ask a friend
      to do it. This is a popular source of stupid and intractibly difficult bugs.

   5. Deep Nesting
      深いネスト

      Nesting depth is one of the few reliable simple indicators of bad code. In general,
      if you're indented more than three levels, probably something is wrong.

      How to avoid this? Sometimes, just simply restructure the code. For example,

          if (condition1) {
             if (condition2) {
                 if (condition3) {
                     if (condition4) {
                         /* something */
                     }
                 }
             }
          }

      would be much better as

          if (condition1 && condition2 && condition3 && condition4)
              /* something */

      Other times, you may have to find a way to pull some code out into a separate unit.
      It is not unheard-of, for example, to replace a deep nest of 'for' loops with a 
      nice simple recursion.

   6. Way Too Much Code
      多すぎるコード

      There's a really strong correlation between bad code and lots of code. In general, if
      you have a good architecture, detailed design and pseudocode, things come out short
      as well as clean. If you have a lot of code, you probably fouled up one of those
      things too.

   7. Way Too General Code
      汎用的過ぎるコード(?)

      Quit trying to "boil the ocean". You will produce way too much code, and
      it will be quite hard to debug. Worse yet, it will be full of bugs, because it will
      not have been tested properly. If you do the simplest thing that can work in your
      specific application, you have a chance.

   8. Parameters, Not Identifiers
      識別子でなくパラメーター

      Never

          if (x == 1) then
              thing1();
          else if (x == 2) then
              thing2();
          /* continued */

      but instead

          thing(x);

      If you have a digit in an identifier, it usually means one of three bad things:
      (1) it should have been a parameter;
      (2) it should have been an array index;
      (3) it's a pun. If you get rid of all of these misuses of identifier digits you will
      have few digits left.

   9. Using 'if' For 'switch'
      'switch' を使うべきところに 'if' を使う

      It is too bad that C-like languages generally don't allow arbitrary expressions to
      be switched on. (Nickle does). That said, if you are switching on numeric constants,
      then by all means use your language's 'switch' construct.

  10. Using 'switch' For Something Strange
      'switch' で奇妙な使い方をする

      There are all-kinds of dumb uses of 'switch'. It's supposed to be used for switching,
      but people use it as a sequencing method ("The 'loop-switch' sequence") and
      in even stranger ways.

             for (i = 0; i < 5; i++) {
                 switch (i) {
                 case 0:
                      first_thing();
                      break;
                 case 1:
                      second_thing();
                      break;
                 /* etc */

      Perhaps my least favorite use is as a replacement for array lookups. Write

          int a[3] = {4, 7, 11};
          for (i = 0; i < 3; i++)
             if (x == a[i])
                 break;

      rather than

          switch(x) {
          case 4:  i = 0; break;
          case 7:  i = 1; break;
          case 11: i = 2; break;
          default: i = 3; break;
          }

      Hopefully the reasons are obvious.

      Never write

          switch(x) {
          case 2:  i = 0; break;
          case 3:  i = 1; break;
          case 4:  i = 2; break;
          case 5:  i = 3; break;
          case 6:  i = 4; break;
          case 7:  i = 5; break;
          }

      instead of

          i = x - 2;

  11. Boolean Expressions and Basic Logic
      ブール式と基本的なロジック

      Not

          !((x <= 1 || y <= 1) && x != 1 && y != 1)

      but

          x >= 1 && y >= 1

      However, be careful and be good at basic logic. Dont let your "simplification" change
      the meaning of the program. For example, the above simplification is wrong.

  12. Code Tangles

      It is quite possible to write "spaghetti code" without using goto. If your
      flow control is complicated, it is probably wrong. Look for opportunities to factor
      the code, and especially to introduce units to make things clearer. Go back to the
      detailed design.

  13. Arrays and Structures. Please
      配列や構造体を使ってくださいな

      For some reason, students seem to be afraid of arrays and structures. Especially
      multi-dimensional arrays. Especially using arrays and structures together.

      何らかの理由で、学生たちは配列や構造体を恐れているようです。特に多次元配列や
      配列と構造体を同時に使うようなことなどを恐れているようです。


      Never write

          int ax1[10], ax2[10], ay1[10], ay2[10];


      for (i = 0; i < 10; i++) {
          ax1[i] = 0;
          ax2[i] = 0;
          ay1[i] = 0;
          ay2[i] = 0;
      }



      Instead, say

          struct {
              int x, y;
          } a[2][10];


      for (i = 0; i < 2; i++) {
          for (j = 0; j < 10; j++) {
              a[i][j].x = 0;
              a[i][j].y = 0;
          }
      }



      You'll find this structure so much nicer to work with.

  14. Weird Dead Code

      When code isn't being used anymore, just remove it. You're using an SCMS (or better be),
      so it isn't lost. It's just out of the way and now no one has to read it anymore.

  15. I Hate C, So I'll Fix It

      Yes, C has a macro preprocessor. It probably shouldn't; it's an extremely blunt 
      tool inserted in the days when C compilers were terrible.

      Try not to use the macro preprocessor for anything clever. In particular, things 
      like the eternal

          #define BEGIN {
          #define END }

      are hateful and awful and sad.

      I feel strongly about understanding that the name of the null pointer in C is 0, and
      the name of the null character is '\0'. You need no macros here: the language is well
      ahead of you on this one.

  16. "My CS 100 Teacher Told Me..."
      だって先生がそういったんだ

      a) "Never use 'goto'". Indeed, this one has become so ingrained that most
         modern students ask "What's a 'goto'?" Well, a "goto" is just
         a way of doing non-local control flow. Here's some actual industry rules about
         goto, drawn from practical experience: (1) Downward goto only, (2) goto only
         within the same unit, (3) goto only when you can't conveniently use a loop
         structure, (4) error handling is the most common use of goto.

      b) "Never use 'magic constants'". If I'm going to be writing a program to
         analyze poker hands, 417 is a magic constant. It should be given an identifying
         symbolic name, especially if it will be used many times and there's a good chance
         it might need to change everywhere. 52, on the other hand, is entirely non-magic,
         as are 4 and 13. These numbers readily identify themselves, and will never have to
         be changed unless the code is being massively refactored anyway. Don't be afraid.

      c) "Never use 'break' or 'continue." This is just crazy. It's highly idiomatic
         to write

          while (true) do {
            /* stuff */
            if (condition)
              break;
            /* more stuff */
          }

      Kernighan and Ritchie call this a "loop-and-a-half" in The C Programming
      Language, and it's used all the time in the real world.

      It pays to be a little careful with break and continue, but they should be used when
      appropriate.

      d) "Never early 'return'." That's such terrible advice I'm tempted to just
         move on. The whole point of having a unit is to be able to encapsulate a computation.
         When the computation is over, get out.

      Why this "rule", then? Because you need to be careful. Make sure you've done
      any cleanup that needs doing before you return. Make sure you aren't returning before
      doing something that needs doing. This is called "programming", and I can
      recommend it.

      The thing about early return is that done properly it can reduce code complexity
      dramatically. In particular, it decreases nesting depth.

■_

■_ Zen of

Numpy 向けのもあるらしい。


Technical Discovery: Zen of NumPy

Here is my attempt at a "Zen of NumPy"

Strided is better than scattered
Contiguous is better than strided
Descriptive is better than imperative (use data-types)
Array-oriented is often better than object-oriented
Broadcasting is a great idea -- use where possible
Vectorized is better than an explicit loop
Unless it's complicated --- then use numexpr, weave, or Cython
Think in higher dimensions


I think there are useful edits as well as more statements that could be added to this 
list. Your feedback is welcome. 

一つ前へ 2010年11月(下旬)
一つ後へ 2010年12月(中旬)

ホームへ


KIMURA Koichi (木村浩一)

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