ときどきの雑記帖 混迷編

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

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

ホームへ

2011年03月20日

■_

部屋の型付け片付けをしていたら、現在は休刊してしまった bit が でてきたのですが、こういう雑誌が今はないのが残念ですね。 まあ出ていたとしてどれだけ売れるのかという疑問はついて回りますが (北米でも Dr Dobb's Jounal とかなくなってますものねえ。紙では)。 電書でもいいのでどうにかならんかしらん(Webは却下で)。

Cao Cao

・ソースコードもGPL化されたし J をやろうかと思ったり

■_ Subversion → Mercurial

CPython のソースコード管理が Mercurialに移行したとか。

Eli Bendersky's website » Blog Archive » Python development switches to Mercurial source control

Python development switches to Mercurial source control

March 18th, 2011 at 10:59 am

The official CPython core development team has finally switched from Subversion to 
Mercurial, after years of planning. This is very good news for both core developers 
and casual contributors.

数年かけた計画ののち、公式の CPython コア開発チームはようやく Subversion から Mercurial
への移行を行いました。これはコア開発チームと casual コントリビューターの双方にとって
とてもよい知らせです。


Working with Subversion when you can't commit changes is very frustrating, because 
you're basically without source control. For experienced developers accustomed to 
having a VCS to protect them at all times, this is hard to get used to. Personally, 
before I became a core Python developer I was using my own Mercurial clone to work on 
patches locally before submitting them to the Issue tracker.

Subversion で変更をコミットできないときは非常にフラストレーションを感じるものでした。
なぜなら、基本的にソースのコントロールがないからです。
常時ソースコードを守るバージョン管理システムを使い慣れた経験豊富な開発者にとって、
そのようなシステムは使うのが難しいものでした。
#んーなんか変だ
わたし個人は、Pythonのコア開発者になる以前には自作の Mercurial クローンを
使って、Issuetracker に submit する前にローカルにパッチを管理していました。

Now, everyone interested contributing to Python can clone the repository and do his 
work locally, committing changes to his heart's wishes and enjoying all the benefits 
of source control. I think this makes the contribution process easier and has a chance 
to attract more contributors to the project, which would be great. Not to mention that 
Mercurial is IMHO a better and more powerful VCS than Subversion in general.

現在、Pyhton に貢献しようという人の誰もがリポジトリのクローンを作れるし、
自分の作業をローカルに行って、changes to his heart's wishes をコミットし、
ソースコードを制御することの利益すべてを享受できるようになりました。


Core developers also benefit from the power of Mercurial vs. Subversion, especially 
when working on non-trivial patches that take longer than a couple of hours to develop. 
These changes can be managed either by commits to a local repo (with a collapse of all 
commits to a single one before pushing), or using the mq extension (which is 
recommended by the new developer guide).

以下略

■_ 構文解析

Partt Parser ってどこかで目にしたような覚えがあるんだけどなあ。 どこだっけ。

journal.stuffwithstuff.com » Blog Archive » Pratt Parsers: Expression Parsing Made Easy

Pratt Parsers: Expression Parsing Made Easy
Pratt Parsers: 構文解析を容易にする

Every now and then, I stumble onto some algorithm or idea that's so clever and such a 
perfect solution to a problem that I feel like I got smarter or gained a new 
superpower just by learning it. Heaps (just about the only thing I got out of my 
truncated CS education) were one thing like this. I recently stumbled onto another: 
Pratt parsers.

When you're writing a parser, recursive descent is as easy as spreading peanut butter. 
It excels when you can figure out what to do next based on the next chunk of code 
you're parsing. That's usually true at the top level of a language where things like 
classes are and also for statements since most start with something that uniquely 
identifies them (if, for, while, etc.).

構文解析ルーチンを記述するとき、再帰下降方式はピーナツバターを塗りたくるくらい
簡単なものです(??)。このやり方は解析するコードの次に来る塊に基づいて次に行うことを
決めることができる場合にはとてもよいものです。これは、
クラスだとか for 文のようなプログラミング言語のトップレベルではふつうは真になります。
なぜなら、何がくるのかを一意に決定可能な (if、for、while などの) 識別子から
そういったものは始まるからです。

But it gets tricky when you get to expressions. When it comes to infix operators like 
+, postfix ones like ++, and even mixfix expressions like ?:, it can be hard to tell 
what kind of expression you're parsing until you're halfway through it. You can do 
this with recursive descent, but it's a chore. You have to write separate functions 
for each level of precedence (JavaScript has 17 of them, for example), manually handle 
associativity, and smear your grammar across a bunch of parsing code until it's hard 
to see.

けれども、式を扱おうとしたときにはトリッキーなものになって今います。


PB & J, The Secret Weapon

Pratt parsing fixes just that. If recursive descent is peanut butter, Pratt parsing is 
jelly. When you mix the two together, you get a simple, terse, readable parser that 
can handle any grammar you throw at it.

(以下略)

© 2008-2009 Robert Nystrom

■_

■_ これなしではいられない5冊

たまにはどーんとアサマシを貼りまくってみるw

Retro Programming: Five Programming Books I Couldn't Survive Without
Five Programming Books I Couldn't Survive Without

There's roughly 400 programming books on my bookshelf.  If I had to reduce it to just five, 

here are the books I just couldn't live without.

   1. Introduction to Algorithms - Cormen, Leiserson, Rivest & Stein.  This 
      programming book provides in depth yet accessible coverage of many algorithms.
      If I want to get the job done as quickly and painfree as possible, I reach for
      Introduction to Algorithms before Knuth's The Art of Computer Programming every
      time.

   2. Compilers: Principles, Techniques and Tools - Aho, Sethi & Ullman.  "
      The Dragon Book" provides an excellent introduction to compiling before 
      getting stuck into the inner workings of analysis, translation, code generation
      and optimisation.

   3. The New Turing Omnibus - Dewdney.  Sitting atop the fun programming books category,
      Dewdney's book offers 66 articles covering a variety of computer science topics and
      recreational computing problems.

   4. Fundamentals of Operating Systems - Lister.  The way the structure of this book 
      mirrors the structure of an operating system makes it an easier point of reference 
      than books such as Krakowiak's Principles of Operating Systems.

   5. Advanced Spectrum FORTH - Thomasson.  Depite being written for a sadly obsolete 
      platform, Advanced Spectrum FORTH remains one of the best FORTH programming books.  
      The source code for the dictionary provides a valuable resource.

Disagree?  Think I've missed out a classic programming book?  Drop me a comment below.

コメントについたものもあわせてどーんといってみよう

アルゴリズムの設計と解析手法 (アルゴリズムイントロダクション)数学的基礎とデータ構造 (アルゴリズムイントロダクション)アルゴリズムイントロダクション 第3巻 精選トピックス

原書は版があがってたり。
Introduction to Algorithms, Third Edition

コンパイラ―原理・技法・ツール (Information & Computing)Compilers: Principles, Techniques, and Tools (2nd Edition)

The (New) Turing Omnibus: 66 Excursions in Computer Science
計算機科学の応用 (チューリングオムニバス―コンピュータサイエンスの旅)機械と言語 (チューリングオムニバス―コンピュータサイエンスへの旅)アルゴリズムとデータ構造 (チューリングオムニバス―コンピュータサイエンスへの旅)計算理論 (チューリングオムニバス―コンピュータサイエンスの旅)

Fundamentals of Operating Systems (Computer Science Series)

Advanced Spectrum FORTH

Operating Systems Design and Implementation (3rd Edition) (Alternative eText Formats)オペレーティングシステム 第3版

Structure and Interpretation of Computer Programs, 2nd Edition (MIT Electrical Engineering and Computer Science)計算機プログラムの構造と解釈

Art of Computer Programming, Volumes 1-4A Boxed Set, The (3rd Edition) (Box Set)
The Art of Computer Programming Volume1 Fundamental Algorithms Third Edition 日本語版 (ASCII Addison Wesley Programming Series)The Art of Computer Programming (2) 日本語版 Seminumerical algorithms Ascii Addison Wesley programming seriesThe Art of Computer Programming Volume 3 Sorting and Searching Second Edition 日本語版 (Ascii Addison Wesley programming series)
The Art of Computer Programming,Volume 4, Fascicle 0 Introduction to Combinatorial Algorithms and Boolean Functions 日本語版 (ASCII Addison Wesley Programming Se)The Art of Computer Programming,Volume 4, Fascicle 3: Generating All Combinations and Partitions【日本語版】 (ASCII Addison Wesley Programming Se)The Art of Computer Programming,Volume 4, Fascicle 2: Generating All Tuples and Permutations[日本語版] (アスキー・アジソンウェスレイシリーズ)The Art of Computer Programming Volume 4, Fascicle 4 Generating All Trees -- History of Combinatorial Generation 日本語版 (ASCII Addison Wesley Programming Series)

珠玉のプログラミング―本質を見抜いたアルゴリズムとデータ構造Programming Pearls (2nd Edition) (ACM Press)

Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition) (Addison-Wesley Professional Computing Series)Effective C++ 原著第3版 (ADDISON-WESLEY PROFESSIONAL COMPUTING SERIES)

Programming Perl

JavaScript Pocket Reference

Mastering the 8088 Microprocessor

Computer Architecture, Fourth Edition: A Quantitative Approach (The Morgan Kaufmann Series in Computer Architecture and Design)コンピュータアーキテクチャ 定量的アプローチ 第4版 (IT Architects’ Archive)


ANSI Common LISP (Prentice Hall Series in Artificial Intelligence)ANSI Common Lisp (スタンダードテキスト)


C Programming Language (2nd Edition) (Prentice Hall Software)プログラミング言語C 第2版 ANSI規格準拠

Scheme手習いThe Little Schemer, 4th Edition

疲れた○| ̄|_

■_

■_

2011年03月19日

■_

ついったは危険だな。やろうと思ってたことがほとんどできなかったw

Binpress この試みは面白そう。 以前にも似たようなものを見たような気がしないでもないけど(勘違い?)。

The source-code marketplace

Binpress is a marketplace for source-code, where developers can buy and sell source-code packages from each other.
  

ラジヲマンの発売はまたも延期になったらしい。

■_ new site

こういうサイトを作るのって英語圏以外にもあるんだろか。 ないような気がする(作れるだけの時間やら技量を持った人は英語のそれを読めば すんでしまうという例のあれとか)。

New Perl news site launches » Perl News

http://perlnews.org/ has just launched and will be providing a source for major 
announcements related to The Perl Programming Language (http://www.perl.org/). Find 
out more at http://perlnews.org/about/ – or if you have a story submit it 
http://perlnews.org/submit/.

All stories are approved to ensure relevance.

Thanks

The Perl News Team.
Welcome to Perl News » Perl News

This is Perl News, the new web site for keeping up with all that is new in the Perl world.

We have a keen group of site editors who have their fingers on the pulse of the Perl 
community and they'll be publishing links here.

If you find a story that we have missed, then please use the submit a story page to 
tell us about it.

■_ How to learn Haskell

Twitter / @Ikegami Daisuke: なんか絶賛されていた、Haskell どうやりゃわか ... から。 stackoverflow は RSS から追いかけづらいんだよなあ。

主なところを幾つか。

functional programming - How to learn Haskell - Stack Overflow

For a few days I've tried to wrap my head around the functional programming paradigm 
in Haskell. I've done this by reading tutorials and watching screencasts, but nothing 
really seems to stick. Now, in learning various imperative/OO languages (like C, Java, 
PHP), excercises have been a good way for me to go. But since I don't really know what 
Haskell is capable of and because there are many new concepts to utilize, I haven't 
known where to start.

数日かけてHaskellを使って関数プログラミングパラダイムを自分の頭に叩き込もうと
していました。それはチュートリアルやスクリーンキャストを使ってできたのですが、
本当に身についたかどうかは疑問です。さて、C や Java、PHPのように色々な
命令型言語であるとかオブジェクト指向言語を学んだときにはエクササイズが
自分にとってはとてもよいやり方でした。しかし、Haskell がどういったものに使えて
一般化すべき多くの新しいコンセプトがあるからだということが良くわかっていなかったので
スタート地点をどこにすべきかわからなかったのです。


So, how did you learn Haskell? What made you really "break the ice"? Also, 
any good ideas for beginning excercises?

そこでお訊きしたいのは、どのようにHaskell を学んだとか
本当に "break the ice" したものは何であったのか、
エクササイズをはじめるにあたっての良いアイデアといったものです。
#ちょー訳


I'm going to order this guide by the level of skill you have in haskell, going from an 
absolute beginner right up to an expert. Note that this process will take many months 
(years?), so it is rather long.

Absolute Beginner 入門者

Firstly, haskell is capable of anything, with enough skill. It is very fast (behind 
only c and c++ in my experience), and can be used from anything from simulations, 
servers, guis and web applications.

まず、Haskell はなんにでも使えます。十分なスキルを持ち合わせていれば。
Haskell は (わたしの経験では C や C++ にだけ引けをとるような) 非常に高速であり、
シミュレーションからサーバー、GUI アプリケーション、Webアプリケーション、
なんにでも使えます。

However there are some problems that are easier to write for a beginner in haskell 
than others. Mathematical problems and list process programs are good candidates for 
this, as they only require the most basic of haskell knowledge to be able to write.

Firstly, a good guide to learning the very basics of haskell is the first 6 chapters 
of learn you a haskell. While reading this, it is a very good idea to also be solving 
simple problems with what you know.

A good list of problems to try is the haskell 99 problems page. These start off very 
basic, and get more difficult as you go on. It is very good practice doing a lot of 
those, as they let you practice your skills in recursion and higher order functions. I 
would recommend skipping any problems that require randomness as that is a bit more 
difficult in haskell.

Once you have done a few of those, you could move on to doing a few of the Project 
Euler problems. These are sorted by how many people have completed them, which is a 
fairly good indication of difficulty. These test your logic and haskell more than the 
previous problems, but you should still be able to do the first few. A big advantage 
haskell has with these problems is Integers aren't limited in size. To complete some 
of these problems, it will be useful to have read chapters 7 and 8 of learn you a 
haskell as well.

こういったものの幾つかを済ませれば、あなたはプロジェクト Euler の問題の
幾つかを解けるようになっているでしょう。このプロジェクトは難易度の fairly good
indication によって、解答した人たちを分類しています。
#なんかちがう
プロジェクト Euler は以前の問題よりも あなたの logic と Haskell とをテストします。

Beginner 初級者

After that you should have a fairly good handle on recursion and higher order 
functions, so it would be a good time to start doing some more real world problems. A 
very good place to start is Real World Haskell (online book, you can also purchase a 
hard copy). I found the first few chapters introduced too much too quickly for someone 
who has never done functional programming/used recursion before. However with the 
practice you would have had from doing the previous problems you should find it 
perfectly understandable.

Working through the problems in the book is a great way of learning how to manage 
abstractions and building reusable components in haskell. This is vital for people 
used to object-orientated (oo) programming, as the normal oo abstraction methods (oo 
classes) don't appear in haskell (haskell has type classes, but they are very 
different to oo classes, more like oo interfaces). I don't think it is a good idea to 
skip chapters, as each introduces a lot new ideas that are used in later chapters.

After a while you will get to chapter 14, the dreaded monads chapter (dum dum dummmm). 
Almost everyone who learns haskell has trouble understanding monads, due to how 
abstract the concept is. I can't think of any concept in another language that is as 
abstract as monads are in functional programming. Monads allows many ideas (such as IO 
operations, computations that might fail, parsing,...) to be unified under one idea. 
So don't feel discouraged if after reading the monads chapter you don't really 
understand them. I found it useful to read many different explanations of monads; each 
one gives a new perspective on the problem. Here is a very good list of monad 
tutorials. I highly recommend the All About Monads, but the others are also good.

Also, it takes a while for the concepts to truly sink in. This comes through use, but 
also through time. I find that sometimes sleeping on a problem helps more than 
anything else! Eventually, the idea will click, and you will wonder why you struggled 
to understand a concept that in reality is incredibly simple. It is awesome when this 
happens, and when it does, you might find haskell to be your favourite imperative 
programming language :)

Intermediate 中級

Once you understand Monads, I think you have made the transition from a beginner 
haskell programmer to an intermediate haskeller. So where to go from here? The first 
thing I would recommend (if you haven't already learnt them from learning monads) is 
the various types of monads, such as Reader, Writer and State. Again, Real world 
haskell and All about monads gives great coverage of this. To complete your monad 
training learning about monad transformers is a must. These let you combine different 
types of Monads (such as a Reader and State monad) into one. This may seem useless to 
begin with, but after using them for a while you will wonder how you lived without 
them.

Now you can finish the real world haskell book if you want. Skipping chapters now 
though doesn't really matter, as long as you have monads down pat. Just choose what 
you are interested in.

With the knowledge you would have now, you should be able to use most of the packages 
on cabal (well the documented ones at least...), as well as most of the libraries that 
come with haskell. A list of interesting libraries to try would be:

    * Parsec: for parsing programs and text. Much better than using regexps. Excellent 
      documentation, also has a real world haskell chapter.
    * Quickcheck: A very cool testing program. What you do is write a predicate that 
      should always be true (eg length (reverse lst) == length lst). You then pass the 
      predicate the quickCheck, and it will generate a lot of random values (in this case 
      lists) and test that the predicate is true for all results. See also the online manual.
    * HUnit: Unit testing in haskell.
    * gtk2hs: The most popular gui framework for haskell, lets you write gtk applications
      in haskell.
    * happstack: A web development framework for haskell. Doesn't use databases, instead
      a data type store. Pretty good docs (another framework would be Turbinado, haven't
      tried it yet though).

Also, there are many concepts (like the Monad concept) that you should eventually 
learn. This will be easier than learning Monads the first time, as your brain will be 
used to dealing with the level of abstraction involved. A very good overview for 
learning about these high level concepts and how they fit together is the 
typeclassopedia article (about half way through, pdf)

    * Applicative: An interface like Monads, but less powerful. Every Monad is Applicative,
      but not vice versa. This is useful as there are some types that are Applicative but are
      not Monads. Also, code written using the Applicative functions is often more composable
      than writing the equivalent code using the Monad functions. See Functors, Applicative
      Functors and Monoids from the learn you a haskell guide.

    * Foldable,Traversable: Typeclasses that abstract many of the operations of lists, so
      that the same functions can be applied to other container types. See also the haskell
      wiki explaination.

    * Monoid: A Monoid is a type that has a zero (or mempty) value, and an operation that
      joins two Monoids together, such that operation x mempty = x. Many types are Monoids,
      such as numbers, with mempty = 0 and operation = plus. This is useful in many situations.

    * Arrows: Arrows are a way of representing computations that take an input and return an
      output. A function is the most basic type of arrow, but there are many other types. The
      library also has many very useful functions for manipulating arrows - they are very
      useful even if only used with plain old haskell functions.

    * Arrays: the various mutable/immutable arrays in haskell.

    * ST Monad: lets you write code with a mutable state that runs very quickly, while 
      still remaining pure outside the monad. See the link for more details.

    * FRP: Functional Reactive Programming, a new, experimental way of writing code that
      handles events, triggers, inputs and outputs (such as a gui). I don't know much about
      this though.

There are a lot of new language features you should have a look at. I'll just list 
them, you can find lots of info about them from google, the haskell wikibook, the 
haskellwiki.org site and ghc documentation.

    * Multiparameter type classes/functional dependencies
    * Type families
    * Existentially quantified types
    * Phantom types
    * GADTS
    * others...

A lot of haskell is based around category theory, so you may want to look into that. 
Unfortunately I don't know any good links for learning category theory for beginners.

Finally you will want to learn more about the various haskell tools. These include:

    * ghc (and all its features)
    * cabal: the haskell package system
    * darcs: a distributed version control system written in haskell, very popular for 
      haskell programs.
    * haddock: a haskell automatic documentation generator

While learning all these new libraries and concepts, it is very useful to be writing a 
moderate-sized project in haskell. It can be anything (eg a small game, data analyser, 
website, compiler). Working on this will allow you to apply many of the things you are 
now learning. You stay at this level for ages (this is where I'm at).

Expert エキスパート

It will take you years to get to this stage (hello from 2009!), but from here I'm 
guessing you start writing phd papers, new ghc extensions, and coming up with new 
abstractions.

Getting Help 助けを得る

Finally, while at any stage of learning, there are multiple places for getting 
information. These are:

いずれにしても、学習のどのステージにあっても、情報を得られる複数の場があります。

    * the #haskell irc channel
    * the mailing lists. These are worth signing up for just to read the discussions 
      that take place - some are very interesting.
    * other places listed on the haskell.org home page

Conclusion (結論)

Well this turned out longer than I expected... Anyway, I think it is a very good idea 
to become proficient in haskell. It takes a long time, but that is mainly because you 
are learning a completely new way of thinking by doing so. It is not like learning 
ruby after learning java, but like learning java after learning c. Also, I am finding 
that my object-orientated programming skills have improved as a result of learning 
haskell, as I am seeing many new ways of abstracting ideas.

I'd suggest joining the #haskell irc channel and asking questions there. That's how I 
learned Haskell. If you go through Real World Haskell as suggested above, real time 
answers to your questions will help greatly. Lots of smart people on #haskell write 
Haskell for fun and for profit, so you'll get lots of good input. Try it!


Try writing easy programs in it.

You can find sample tasks in various textbooks, probably.

I wouldn't recommend sticking to Haskell/FP textbooks, just try to do simple things 
with it: calculations, string manipulations, file access.

After I solved a dozen, I've broke the ice :)

After that, read a lot on advanced concepts (Monads, Arrows, IO, recursive data 
structures), because haskell is infinite and there are a lot of them.


site design / logo © 2011 stack exchange inc;
user contributions licensed under cc-wiki with attribution required

やっぱモナドかいっ!w → Once you understand Monads, I think you have made the transition from a beginner haskell programmer to an intermediate haskeller.

■_ sed で

OKWave から。

正規表現:  (111)-(222)-(333) | OKWave

正規表現:  (111)-(222)-(333) から
(333)を取得したいと考えています。

()で囲まれた数字のうち、最後のものを取得するというもので、
この、最後のという考えを実装することができずに困っています。

なぜ最後にこだわるかというと、以下のような例があるからです。
◆ (111)english(222)
◆ (111)日本語(222)日本語

文字列中に含まれる()で囲まれた数字のうち、最後のものを取得する正規表現を教えてください。

投稿日時 - 2011-03-19 16:59:55
ANo.1


> 以下のような例があるからです。

この例の両方ともが該当するのか、それとも前者だけが該当するのかで大幅に難易度が変わってきますが、どっちですか?

投稿日時 - 2011-03-19 17:10:14
補足

レスいただきありがとうございます。
比重としては下側  (111)日本語(222)日本語  を意識しています。
文章中から拾いたいため、かならず最後になる保証は難しいためです。 よろしくお願いします。

投稿日時 - 2011-03-19 17:18:46
ANo.2

正規表現は、基本、最長一致なので、「^.*」等を使えば、「最後」の表現は簡単です。

ただ、「最後だけ」となると、
・前の部分を除外する
・まさに最後だけにヒットさせる
といった表現をする必要になります。

お尋ねの部分は、ここの部分かと思いますが、これは使っているツールによって異なるので、お
使いのツールが解れば、他の方からフォローが気易いと思います。

投稿日時 - 2011-03-19 17:20:49
ANo.3

私は正規表現マスターという訳でもないですが、最後のというのを一発で表現するのは難しいような気がします。
以下のどちらかの方法はどうでしょうか?

1) ()の個数が2個の場合と3個の場合を区別し、場合分けする。
2) 1段階目で()の最長マッチをし、2段階目で最後の()の部分を取得する。

投稿日時 - 2011-03-19 17:24:19
ANo.4

()で囲まれた数字のうち、最後のもの「だけ」を取得することは、多分正規表現だけでは無理
です。その検索にはどうしても、「最後の数字から行末まで」という条件を追加しなければなら
ないので、数字の後の文字列まで引っかかってしまいます。それでもよければ、以下の正規表現
で可能です。

\([0-9]+\)[^(]*[^0-9]*[^)]*$

あくまでも最後の数字だけにしたい場合は、Perl・ruby・awkなどの文字列処理に強いスクリプ
ト処理系のお世話にならなければ無理でしょう。

投稿日時 - 2011-03-19 17:41:03

ANo.5

何らかのプログラミング言語で使うのでしょうから、 .*\((.*)\) という正規表現でマッチさせ
て、カッコにマッチする部分を抜き出す・・・ 多くのスクリプト言語では $1 ・・・。

投稿日時 - 2011-03-19 17:46:27

sed -ne "s/^.*\(([^()][^()]*)\)[^()]*$/\1/p" こんなとこかな。 なんかしらんけど、Cygwin の sed だと期待通りに動かなかったので焦った。 PCRE をリンクした GNU grep なら、先読みを活用して -o オプションで抜き出せると思う。

■_

2011年03月18日

■_

ラジヲマン、本当に出るんだろうか…

■_

二日分

■_ おまじないなんか存在しない

Twitter / @Hirofumi Saito: これね。再構築ということをしないとダメなんだよね。そ ... 経由で。

awkで$0出力するときにOFS指定が無視られる問題 - kakenmanの日記

awkでOFS指定しても出力のセパレータが無視される時がある問題がやっと解決しました.

やりたいこと

    * 何らかのセパレータで区切られたcsvファイルの中から,特定の条件を満たす行を,セパレータを変えて出力する

まぁ,こう言われればみんなawkでやろうとしますよね?そうでもない?

例えば以下のようなカンマ区切りのcsvファイル

a,b
d,c
a,e
e,d

この中から,一つ目のフィールドが"a"の行のみ,セパレータをカンマからプラスに変えて出力したいとします.

つまり,

a+b
a+e

が望む形.

この時,とりあえず思いつくのは,

% awk -F "," 'BEGIN{OFS="+"}{ if($1=="a"){print $0}}' test.csv

ですよね.OFSは出力セパレータ.始めに出力セパレータにプラスを指定しておいて,$0で全フィールド出力.

ところが,これだとうまくいきません.結果はこうなります.

a,b
a,e

ちゃんと条件は取れているのですが,セパレータが変更されていません.ですが,実は以下のように書くと意図した通りに動きます.

% awk -F "," 'BEGIN{OFS="+"}{ if($1=="a"){print $1,$2}}' test.csv

結果が以下です

a+b
a+e

何故$0(全出力)ではうまくいかず,$1,$2と全部指定するとうまくいくのかずっと謎でした.この例ではフィールドが二つだからいいですが,多くなってくると,さらにフィールドの数が可変になってくると,for文を使って全フィールド出力することになり,たったこれだけの処理なのにやけにコマンドが汚くなります.

実は理由は今でも謎ですが,以下のようにするとうまくいくことが分かりました.

% awk -F "," 'BEGIN{OFS="+"}{$1=$1; if($1=="a"){print $0}}' test.csv

結果が以下です

a+b
a+e

上記のように,$1=$1というおまじないを入れることでうまくいくようになります.

理由はかなり謎ですが,どうやら$1=$1とすることでカラムの再構成が行われてどうとか・・・?

どちらにせよ,$0で指定する場合と$1,$2...$NFで指定する場合で結果が違うというのは何か気持ち悪いです.

さいとうさんのコメントにもあるように、 $0の「再構成」をしないと$0は入力されたものそのままです。 入力を読み込んだときにフィールドに分解して、 それをOFSで連結したものを持っているわけではありません (フィールド分割そのものはもちろん入力時に行います)。


As mentioned previously, a `print' statement contains a list of items
separated by commas.  In the output, the items are normally separated
by single spaces.  However, this doesn't need to be the case; a single
space is only the default.  Any string of characters may be used as the
"output field separator" by setting the built-in variable `OFS'.  The
initial value of this variable is the string `" "'--that is, a single
space.

  

まったく入力レコードの内容と関係ないものでもOFSで繋げてそれを出力するというだけの話。 だから、print $0, $0 とやるとOFSを挟んで$0を二つ出力します。 じゃあ $1=$1 ってなによ? ってのもこの gawk の info を見ればちゃんと書いてます。

3.4 Changing the Contents of a Field
====================================

The contents of a field, as seen by `awk', can be changed within an
`awk' program; this changes what `awk' perceives as the current input
record.  (The actual input is untouched; `awk' _never_ modifies the
input file.)  Consider the following example and its output:

     $ awk '{ nboxes = $3 ; $3 = $3 - 10
     >        print nboxes, $3 }' inventory-shipped
     -| 25 15
     -| 32 22
     -| 24 14
     ...

The program first saves the original value of field three in the
variable `nboxes'.  The `-' sign represents subtraction, so this
program reassigns field three, `$3', as the original value of field
three minus ten: `$3 - 10'.  (*Note Arithmetic Ops::.)  Then it prints
the original and new values for field three.  (Someone in the warehouse
made a consistent mistake while inventorying the red boxes.)

   For this to work, the text in field `$3' must make sense as a
number; the string of characters must be converted to a number for the
computer to do arithmetic on it.  The number resulting from the
subtraction is converted back to a string of characters that then
becomes field three.  *Note Conversion::.

   When the value of a field is changed (as perceived by `awk'), the
text of the input record is recalculated to contain the new field where
the old one was.  In other words, `$0' changes to reflect the altered
field.  Thus, this program prints a copy of the input file, with 10
subtracted from the second field of each line:

     $ awk '{ $2 = $2 - 10; print $0 }' inventory-shipped
     -| Jan 3 25 15 115
     -| Feb 5 32 24 226
     -| Mar 5 24 34 228
     ...

(略)

   Finally, there are times when it is convenient to force `awk' to
rebuild the entire record, using the current value of the fields and
`OFS'.  To do this, use the seemingly innocuous assignment:

     $1 = $1   # force record to be reconstituted
     print $0  # or whatever else with $0

This forces `awk' rebuild the record.  It does help to add a comment,
as we've shown here.

   There is a flip side to the relationship between `$0' and the
fields.  Any assignment to `$0' causes the record to be reparsed into
fields using the _current_ value of `FS'.  This also applies to any
built-in function that updates `$0', such as `sub' and `gsub' (*note
String Functions::).

  

めんどうなので訳はつけない :)

2011年03月17日

■_

今日は色々と見たくなかったものを見てしまった

(翻訳)開発者の寿命について思うこと - YAMAGUCHI::weblog さーきをこーされてたーーー○| ̄|_

いいなこれw Added an uncle sam meme by tenderlove for drbrain's meme - Pull Request - GitHub

■_ short coding

スタック操作子

Retro Programming: Efficiency in Forth

Sunday, 13 March 2011

Efficiency in Forth

I'm busy implementing my own Forth at the moment and it's taking a little longer than 
anticipated. Each Forth word is a puzzle in itself:

    * What's the least number of words needed to write it?
      記述するのに必要な最小のワード数は?

    * What's the most efficient implementation?
      最も効率の良い実装はなにか?

For example, take a look at Implementing MIN in Forth without Conditional Code. The 
smallest version of MIN is 2 words shorter than eForth's MIN.

たとえばForthのMINを、条件判断抜きに実装した場合を例に取ると
その最小の命令数は eForthのそれよりも2ワード短いものです。

Even words with a trivial implementation can pose an interesting problem. For example 
which of the following is most efficient:

Jones Forth TUCK

: TUCK DUP -ROT ;


Alternative TUCK

: TUCK SWAP OVER ;


If DUP, -ROT, SWAP and OVER are all primitive, the alternative implementation will 
execute two fewer instructions on an 80x86 Forth. However, -ROT is often implemented 
in Forth which would cause the Jones Forth TUCK to be substantially slower. Here's a 
typical implementation of -ROT:

: -ROT SWAP >R SWAP R> ;


If you can think of an alternative two word implementation of TUCK or four word 
implementation of -ROT, please let me know. :-)


使っているワードの実装を知らないと、短くして効率を良くしたつもりが 性能を落としたりしてしまうこともありうるというお話し。 tuckってのは↓の一覧にあるように スタックの二番目にある要素のコピーをスタックトップに積むというもの。

データスタック用ワード - Gforth マニュアル

5.6.1 データスタック用ワード

drop       w –        core       “drop”

nip       w1 w2 – w2        core-ext       “nip” (訳注: swap して drop する)

dup       w – w w        core       “dupe”

over       w1 w2 – w1 w2 w1        core       “over” (訳注: w1 をコピーして積む)

tuck       w1 w2 – w2 w1 w2        core-ext       “tuck” (訳注: swap して over する)

swap       w1 w2 – w2 w1        core       “swap”

pick       S:... u – S:... w        core-ext       “pick”

実際のスタック変化は ( x0 ... xu u -- x0 ... xu x0 ) である (訳注: u を消費して、新たな TOS から u 個分下の要素をコピーして積む)。

rot       w1 w2 w3 – w2 w3 w1        core       “rote” (訳注: w1 を TOS へ移す)

-rot       w1 w2 w3 – w3 w1 w2        gforth       “not-rote” (訳注: rot rot)

?dup       w – S:... w        core       “question-dupe”

実際のスタック変化は ( w -- 0 | w w ) である。すなわち、w がゼロ以外なら dup する。

roll       x0 x1 .. xn n – x1 .. xn x0         core-ext       “roll” (訳注: pick でコピーする代わりに TOS へ移す)

2drop       w1 w2 –        core       “two-drop”

2nip       w1 w2 w3 w4 – w3 w4        gforth       “two-nip”

2dup       w1 w2 – w1 w2 w1 w2        core       “two-dupe”

2over       w1 w2 w3 w4 – w1 w2 w3 w4 w1 w2        core       “two-over” (訳注: w1 と w2 をコピーして積む)

2tuck       w1 w2 w3 w4 – w3 w4 w1 w2 w3 w4        gforth       “two-tuck” (訳注: 2swap して 2over する)

2swap       w1 w2 w3 w4 – w3 w4 w1 w2        core       “two-swap”

2rot       w1 w2 w3 w4 w5 w6 – w3 w4 w5 w6 w1 w2        double-ext       “two-rote”

■_

で、もう一個。

Retro Programming: Implement MIN in Forth without Conditional Code
Monday, 1 June 2009

Implement MIN in Forth without Conditional Code
ForthのMINを条件分岐のコードを使わずに実装せよ

While lurking in the #forth channel on irc.freenode.net I was pointed to an interesting 
problem from the Gforth tutorial. The problem is to implement MIN in Forth without any 
conditionally executed code.

DO, LOOP, BEGIN, UNTIL, REPEAT, WHILE, IF, ELSE and THEN are all forbidden.  MIN removes 
the top two values from the data stack then puts the lower of the two back on.

DO、LOOP、BEGIN、UNTIL、REPEAT、WHILE、IF、ELSE、THEN はすべて使ってはならない。
MIN はデータスタックからふたつの値を取り出して、そのうちの小さなほうを
スタックに再度積む。

Can you implement MIN under these conditions? If so I challenge you implement it in as 
few Forth words as possible! Let me know if your implementation is under 10 words :-)

上記の条件の下で、MINを実装できるか?
もしできるのなら、可能な限り少ないワード数で実装することに挑戦してみてほしい。
10ワード未満で実装できたら教えてね :-)

7 comments:

tardieu said...

    : min 2dup - abs - + 2 / ;

    If a < b, |a-b| = b-a, so min = a = ((a+b)-(b-a))/2 = (a+b)-|a-b|)/2.

    If b < a, |a-b| = a-b, so min = b = ((a+b)-(a-b))/2 = (a+b)-|a-b|)/2.

    So ((a+b)-|a-b|)/2 is always the right answer. 7 words, 6 if you have a builtin 2/.
    1 June 2009 14:55 

John said...

    tardieu: that's a neat solution. My technique looks ugly by comparison.

    However, it's possible to implement MIN in less words :-)
    1 June 2009 22:11 

llogiq said...

    : min 2dup > 1+ pick 2nip ;
    3 June 2009 01:42 

John said...

    llogiq: great solution, mine is similar:

    : min 2dup < 1+ roll nip ;
    3 June 2009 08:31 

llogiq said...

    Great - in fact I like your solution more than my own. Btw. I did not "get" forth, until researching it a little bit for solving this small puzzle and finding Rich Jones' impressively documented implementation. Thank you.
    3 June 2009 16:25 

Anonymous said...

    Er...what Forth system are you using? Admittedly 2nip is not a standard word, but usually it is a double cell version of nip, not "nip nip", so 2dup > 1+ pick 2nip would not be a solution...
    3 June 2009 18:00 

llogiq said...

    Anonymous: You're right. Thank you for finding my error.
    8 June 2009 00:23 

んー、比較の動作はどうなんだっけか。 解答の動作が良くわからないので追いかけてみた。

真偽フラグと比較 - Gforth マニュアル

3.17 真偽フラグと比較

すべてのビットが 0 であるものが偽フラグであり、整数として解釈された場合はゼロに等しい。
逆に、本来の真フラグはビットがすべて 1 であるものであり、(2 の補数表現) 符号付き整数の 
-1 に等しい。しかし、例えば if など、たいての場合は、ゼロ以外の値はすべて真フラグと見
なされる。

ふむ。

数値比較用ワード - Gforth マニュアル

5.5.4 数値比較用ワード

等値かどうかに関する数値比較用ワード (= <> 0= 0<> d= d<> d0= d0<>) は、
符号付きと符号なしの両方の整数に使用可能である。

<       n1 n2 – f        core       “less-than”

<=       n1 n2 – f        gforth       “less-or-equal”

<>       n1 n2 – f        core-ext       “not-equals”

=       n1 n2 – f        core       “equals”

>       n1 n2 – f        core       “greater-than”

>=       n1 n2 – f        gforth       “greater-or-equal”

0<       n – f        core       “zero-less-than” (訳注: n が 0 より小さければ真)

0<=       n – f        gforth       “zero-less-or-equal”

0<>       n – f        core-ext       “zero-not-equals”

0=       n – f        core       “zero-equals”

0>       n – f        core-ext       “zero-greater-than” (訳注: n が 0 より大きければ真)

0>=       n – f        gforth       “zero-greater-or-equal”

とすると。

    : min 2dup >l; 1+ pick 2nip ;

+-+-+
|3|7|
+-+-+
+-+-+-+-+
|3|7|3|7| ←スタックトップと二番目をコピー
+-+-+-+-+
+-+-+-+-+-+
|3|7|3|7| | 比較してその結果がスタックトップに
+-+-+-+-+-+
+-+-+-+-+-+
|3|7|3|7| | 結果の数値に1たす
+-+-+-+-+-+
+-+-+-+-+-+
|3|7|3|7|7| pick する
+-+-+-+-+-+
+-+-+-+
|3|7|3| 2nip する
+-+-+-+

    : min 2dup < 1+ roll nip ;

+-+-+
|3|7|
+-+-+
+-+-+-+-+
|3|7|3|7|
+-+-+-+-+
+-+-+-+-+-+
|3|7|3|7| |
+-+-+-+-+-+
+-+-+-+-+-+
|3|7|3|7| |
+-+-+-+-+-+
+-+-+-+-+
|3|7|3|7|  ← roll の結果
+-+-+-+-+
+-+-+-+
|3|7|3| nip
+-+-+-+

■_ co-

Bloggy Badger: I understand comonads

Saturday, April 28, 2007

I understand comonads

Upon discovering the incredible coolness of monads, I decided that the closely related 
concept of comonads had to be at least as interesting. Unfortunately, far fewer people 
seem to be interested in this little underestimated cousin, at least not enough for 
anyone to post a spacesuit metaphor for them. But as always, when proper documentation 
is lacking, it suffices to ask the source.


class Monad m where
  (>>=) :: m a -> (a -> m b) -> m b
  return :: a -> m a

class Comonad w where
  (=>>) :: w a -> (w a -> b) -> w b
  extract :: w a -> a 


なにがなにやら。

■_

対決 Common Lisp vs. Emacs Lisp (うそ

What advantages does common lisp have over emacs lisp, and vice versa? : lisp

What advantages does common lisp have over emacs lisp, and vice versa? (self.lisp)


Common Lisp:

    * Has namespaces
    * Has lexical scope
    * Has default values for optional arguments

Emacs Lisp:

    * Runs in Emacs
    * Hey, at least it's not Java.


    Has default values for optional arguments

Note that the cl package provides the full Common Lisp defun as defun*, so you can 
have these. But something that can't be provided is multiple return values.


Different default settings and performance criteria.

Emacs lisp just exists because there is a lot of code written in it, common lisp is 
strictly better. But the differences between scheme and common lisp is more a matter 
of taste.

■_

2011年03月16日

■_

おかしいな、何でもうこんな時間…

■_

■_ array of array

gawk 4.0で増えた(る)機能に、本物の配列の配列もあったと。

8.7 Arrays of Arrays 配列の配列
====================

`gawk' supports arrays of arrays. Elements of a subarray are referred
to by their own indices enclosed in square brackets, just like the
elements of the main array.  For example, the following creates a
two-element subarray at index `1' of the main array `a':

'gawk'は配列の配列をサポートしています。主配列 (main array) の要素と同じように、
部分配列 (subarray)の要素は角カッコで囲まれている固有の添え字によって参照されます。
たとえば次の例では主配列 'a' の添え字 '1' にある二要素の部分配列を生成します。


     a[1][1] = 1
     a[1][2] = 2


   This simulates a true two-dimensional array. Each subarray element
can contain another subarray as a value, which in turn can hold other
arrays as well. In this way, you can create arrays of three or more
dimensions.  The indices can be any `awk' expression, including scalars
seperated by commas (that is, a regular `awk' simulated
multidimensional subscript). So the following is valid in `gawk':

これは本物の二次元配列をシミュレートします。
各サブ配列の要素は値としてもう一つのサブ配列を持てて、
このサブ配列もまた同様に別の配列を保持できます。
このやり方で三次元配列やそれ以上の次元の配列を作り出せます。
配列の式にはカンマ (つまり通常の'awk'での多次元添え字のシミュレート)
で区切られたスカラーを含めて任意の 'awk' の式を使えます。
ですから次の例は 'gawk' では vaild なものです:


     a[1][3][1, "name"] = "barney"

   Each subarray and the main array can be of different length. In
fact, the elements of an array or its subarray do not all have to have
the same type. This means that the main array and any of its subarrays
can be non-rectangular, or jagged in structure. One can assign a scalar
value to the index `4' of the main array `a':

各サブ配列と主配列は異なる長さであってもかまいません。
実際には、配列やサブ配列の要素はすべてが同じ型である必要もありません。
This means that the main array and any of its subarrays
can be non-rectangular, or jagged in structure. 
主配列 'a' の index '4' にスカラー値を設定することも可能です:

     a[4] = "An element in a jagged array"

   The terms "dimension", "row" and "column" are meaningless when
applied to such an array, but we will use "dimension" henceforth to
imply the maximum number of indices needed to refer to an existing
element. The type of any element that has already been assigned cannot
be changed by assigning a value of a different type. You have to first
delete the current element, which effectively makes `gawk' forget about
the element at that index:

“次元”であるとか“列”、“行”といった用語はこういった配列に適用するのには意味がありません。
しかし、既存の要素を参照するのに必要となる添え字の最大値を表すのにここでは“次元”を使います。
すでに代入された要素の型はすべて異なる型の値を代入することによって変更することはできません。
まずはじめに その位置にあった要素について効率よく 'gawk' に忘れさせるために
current 要素を削除しなければなりません

     delete a[4]
     a[4][5][6][7] = "An element in a four-dimensional array"

This removes the scalar value from index `4' and then inserts a
subarray of subarray of subarray containing a scalar. You can also
delete an entire subarray or subarray of subarrays:

これは添字 '4' からスカラー値を削除し、それから
スカラーを保持しているサブ配列のサブ配列のサブ配列を挿入しています。
サブ配列丸ごとや、サブ配列のサブ配列を削除することも可能です。

     delete a[4][5]
     a[4][5] = "An element in subarray a[4]"

   But recall that you can not delete the main array `a' and then use it as a scalar.

ただし、主配列 'a' を削除してから再度 'a' をスカラーとして使うことは許されないことを
忘れないでください。

   The built-in functions which take array arguments can also be used with subarrays. 
For example, the following code fragment uses `length()' to determine the number of 
elements in the main array `a' and its subarrays:

配列を引数で受け取る組み込み関数はサブ配列に対しても使用可能です。
たとえば以下のコード片は主配列 'a' やそのサブ配列の要素数を決定するために
‘length()'を使っています

     print length(a), length(a[1]), length(a[1][3])

This results in the following output for our main array `a':

     2, 3, 1

The `SUBSCRIPT in ARRAY' expression (*note Reference to Elements::)
works similarly for both regular `awk'-style arrays and arrays of
arrays. For example, the tests `1 in a', `3 in a[1]', and `(1, "name")
in a[1][3]' all evaluate to one (true) for our array `a'.

`SUBSCRIPT in ARRAY' という式は通常の awk 形式の配列と
配列の配列の両方に対して同様に動作します。たとえば
`1 in a', `3 in a[1]', `(1, "name") in a[1][3]' といったテスト
all evaluate to one (true) for our array `a'.
はすべて 'a' という配列

   The `for (item in array)' statement (*note Scanning an Array::) can
be nested to scan all the elements of an array of arrays if it is
rectangular in structure. In order to print the contents (scalar
values) of a two-dimensional array of arrays (i.e., in which each
first-level element is itself an array, not necessarily of the same
length) you could use the following code:

  
`for (item in array)' 文は配列の配列が rectangular in structure であれば
そのすべての要素を走査するためにネストできます。二次元の配列の配列
(i.e. それぞれの第一レベルの要素がまた配列であるような配列で、
第一レベルの要素がすべて同じである必要はありません) の
内容(スカラー値)を出力するのに次のようなコードを使えます:

     for (i in array)
         for (j in array[i])
             print array[i][j]

   If the structure of a jagged array of arrays is known in advance,
you can often devise workarounds using control statements. For example,
the following code prints the elements of our main array `a':

ジャグ配列の配列 (jagged array of array) の構造が known in advance であれば、
制御文を使って devise workarounds できるのがほとんどです。
たとえば以下のコードはmain 配列 'a' の要素群を出力します

     for (i in a) {
         for (j in a[i]) {
             if (j == 3) {
                 for (k in a[i][j])
                     print a[i][j][k]
             } else
                 print a[i][j]
         }
     }

   Recall that a reference to an uninitialized array element yields a
value of `""', the null string. This has one important implication when
you intend to use a subarray as an argument to a function, as
illustrated by the following example:

初期化されていない配列要素に対する参照の結果は空文字列 "" になることを思い出してください。
これは、以下に挙げる例のようにサブ配列を関数の引数として使おうとするときには
重要な implication です

     $ gawk 'BEGIN { split("a b c d", b[1]); print b[1][1] }'
     error--> gawk: cmd. line:1: fatal: split: second argument is not an array

   The way to work around this is to first force `b[1]' to be an array
by creating an arbitray index:

これに対する回避策は初めに 'b[1]' を任意の添字で作ってしまうことで強制的に配列にしてしまう
というのものです。

     $ gawk 'BEGIN { b[1][1] = ""; split("a b c d", b[1]); print b[1][1] }'
     -| a

■_

2011年03月15日

■_

眠気に負けた

■_

InfoQ: SQL Server 2011の列ベースのストレージ

Microsoftの発表では、14億4千万の行を保持する1TBのテーブルを利用するとき、列指向の問い
合わせを実行すると、CPU時間で16倍のスピード改善と455倍もの経過時間の改善が見られたとい
うことだ。実質的には501秒かかっていた問い合わせが1.1秒までに改善するということだ。この
テストは256GBのメモリと32の論理プロセッサを持ったマシンで実施された。
InfoQ: Column-based Storage in SQL Server 2011

When using a table with 1 TB of data and 1.44 billion rows, Microsoft claims that 
column-orientated queries saw a 16X speed-up in CPU time and a whopping 455X 
improvement in elapsed time. In real terms this means a query that took 501 seconds 
originally was reduced to merely 1.1 seconds. This test was performed on a 32-logical 
processor machine with 256GB of RAM.

「実質的には~までに改善」の実質的の使い方に違和感があるのだけど 「In real terms」って「実質的に(な)」となるのね。 むー。

■_

■_

■_

2011年03月14日

■_

運行されている本数は半分から6割程度だったもののかなーり楽な通勤で、 いろいろ苦労された方にはちと申し訳ない気も。 あんまり余裕を見すぎて、始業一時間前くらいについちゃったんですけどね ;)

なんのかんので読み飛ばす未読が多かったり。 時間的には多少は余裕があったはずなんですが。

■_ '-'

2011-03-13 - Maeの(Mae向きな)日記

『数学ガール/乱択アルゴリズム』を読んでます。数学ガールシリーズも本書で4冊目ですが,
乱択アルゴリズムでは擬似コードでアルゴリズムが紹介されています。読者の多くの方はプログ
ラミング言語に親しまれている方だと思いますが,ひょっとして,本書を通して初めてプログラ
ムに触れるという方もいらっしゃるかもしれないということで,何個かプログラムにしてみまし
た。Rubyで書いています。

(略)

あと,本では手続きの名前を`-'で区切っていますが,これでは引き算の意味になってしまいま
すので,`_'に変更しています。

def sentinel_linear_search(a, n, v)
  a[n] = v                      # 添字0からはじまるから
  k = 0                         # 同上
  while a[k] != v
    k = k + 1
  end
  if k <= n
    return "見つかる"
  end
  return "見つからない"
end

以下略

Perl 6でメソッド名の一部に '-' が使えるように見えるコード片を以前見かけたのですが、 やっぱり使えるとうれしいですよね(って少数派かしらん)。 シフトキー押さないで入力できるし(笑)

字句解析と構文解析が面倒になるので、うれしさと面倒を天秤にかけるとやっぱきびしいか。 たとえば演算子の前後には空白をひとつ以上置かなければならないといった具合にすれば (COBOLだ)、楽にはなるでしょうが果たして受け入れられるかどうか。 既存の言語の場合はそういうのを持ち込むと互換性が崩れますしね。

■_ what is "coder"?

駄目なプログラマの特徴

601 仕様書無しさん [sage] 2011/02/16(水) 02:23:37 ID: Be:
    別にVBしか出来なくてもプログラマなんだし、
    プログラマとしてまだまだだと思うなら、PHPとかJavaあたりから勉強すればいいんじゃね?

    駄目なプログラマってのは、
    新しい言語や技術に見向きもせず、
    今の持ってる能力だけで完璧とか言ってるような人間 

602 仕様書無しさん [sage] 2011/02/16(水) 02:47:42 ID: Be:
    >>601
    ロートルのCOBOL使いでも、保守や更新で呼び出されるなら立派なプログラマ。
    プログラムと、扱うべき内容の両方を熟知してこそのプログラマ。
    コンピュータや言語だけ理解してるのはただのコーダー。 

622 仕様書無しさん [sage] 2011/02/26(土) 10:09:19.39 ID: Be:
    >>602
    コーダーの語源を教えてください
    SEやPGみたいに聞いたことがないので 

623 仕様書無しさん [sage] 2011/02/26(土) 10:12:28.86 ID: Be:
    >>602
    >>622を訂正
    SEやPGのような単語を周りに使う人がおらず、ウェブで見かける「SEがどうの」「PGがどうの」という言葉がピンと来ません。
    コーダーという単語もどのような場面で使われているかがわかりません。
    コーダーの具体的な意味やどのような場面で使われいるのか、また慣わしを教えてください

624 仕様書無しさん [sage] 2011/02/26(土) 10:26:01.90 ID: Be:
    >>623
    昔、まだパンチカードでプログラムを入力していた頃、
    プログラマってのは数式やフローチャートを書くところまでで、
    それをソースコードにするのはコーダーの仕事だったんだよ。

    で、コーダーはソースコードをパンチャーさんに渡して、
    パンチャーさんはタイプライタ入力してカード穿孔機でカードをつくって、
    パンチャーさんはカードをオペレータさんに渡して、
    オペレータさんがカードリーダーにセットして実行していたわけ。

    そのころの名残りで、
    単に上流からの指示通りにソースコードを書くだけの人をコーダーと呼ぶ。 

625 仕様書無しさん [sage] 2011/02/26(土) 15:27:17.02 ID: Be:
    >>624
    指示どおりに書くことすらまともに出来ないヤツが多いんだから
    優秀なコーダーにはそれなりの評価をすべきだと思う 

626 仕様書無しさん [sage] 2011/02/26(土) 16:13:13.73 ID: Be:
    >>609
    プログラマとして最高にいいコメントだな
    そういうやつが会社にいるなら、教わることは多いと思うぞ 

627 仕様書無しさん [sage] 2011/02/26(土) 16:15:49.55 ID: Be:
    >>625
    そりゃおまいのレベルの指示をコーダーにだすからだよ
    そのレベルの指示はPGにだせ 

628 仕様書無しさん [sage] 2011/02/26(土) 17:35:28.08 ID: Be:
    今時、SEとかPGなんて老害の決めたやり方での、老害の区分でしかない 

629 仕様書無しさん [sage] 2011/02/26(土) 18:22:15.23 ID: Be:
    >>624-625
    ありがとうございます!

    昔のプログラマとコーダーの働きがはっきりわかれていたころの名残なのですね 

630 仕様書無しさん [sage] 2011/02/26(土) 18:24:21.35 ID: Be:
    PM、PL、SE、PGなんて単価と責任の区別をつけるだけのものさ。 

631 仕様書無しさん [sage] 2011/02/26(土) 19:10:15.42 ID: Be:
    近代日本語学I
    問. 以下は何の略語か、答えなさい。

    PM・・・
    PL・・・
    SE・・・
    PG・・・ 

どーもPGって略称がしっくりこないんですよねえ。

■_ いいね

Python 生誕20周年 - YAMAGUCHI::weblog の方なんですが、御自身のプロファイルに 翻訳とかやってます。ご褒美お待ちしてます! Amazon ほしい物リスト とあって、単に何か贈ってくれと書かれるよりはおおそうか、とその気になりそうな感じがします。 で、この方のリストに載っている本でわたしが持ってるのが何冊かあるんですが やっぱりリストからぽちっとなしないといけないのかしらん。

■_ 比べてみる

素数ネタのあれから。shinh さんのところにあったリストで sumim さんの Smalltalk 版を見つけたのでどんなものかと読んでみた。

Twitter / @Kazuhiro Inaba: 素数を数えるプログラム、面白いのが全然思いつかない。 ...

素数を数えるプログラム、面白いのが全然思いつかない。うーん

(1..23**45).inject{|*x|x[1,x.inject(&:%)].inject(method(:p),&:[]);x.inject(2,&:*)}

そもそもこっちからして良くわかってないというのはおいといて。

Twitter / @sumim: bit.ly/fyzrIc 面白い。ネタバレをSma ...

面白い。ネタバレをSmalltalkで書くとこうか。

→(2 to: 100) inject: 1 into: [:m :e | (m isDivisibleBy: e) ifFalse: [Transcript cr; show: e]. 2*m*e]

先頭の (1..23**45) と (2 to: 100) の違いは本質的でないので無視して


{          |*x|  x[1, x.inject(&:%)].inject(method(:p),&:[]);  x.inject(2,&:*) }

1 into: [:m :e | (m isDivisibleBy: e) ifFalse: [Transcript cr; show: e]. 2*m*e]

んーー。Ruby 版は % でフィルタリングしてその結果のリストを 次の inject に流しこんでるけど Smalltalk版 は違う? まてまてそもそも Ruby 版の2個目の inject がやってるのは何かというと… あれ? Smalltalk 版の ifFalse の後のブラケットにくっついてる '.' ってナニモノ?

■_

■_

2011年03月12日

■_

停電どうなるんだろう…

■_

ベイスターズが絡んでたので :) バカが征く

バカが征く

年下の同僚から『どうしたら腕が上がるんですかね?』
みたいな話を振られて。そのときは、まぁ、いろんな
ことをしゃべったんだけど。

改めて考えてみて、結局のところはプロ意識を持つことが
一番最初なんだというのが自分の結論になった。

日経のサイトに権藤博氏のコラムがあって、それが非常に
味わい深くて好きなんだけど:

http://www.nikkei.com/sports/column/page/p=9694E2E6E2E0E0E2E3E2E6E2EAE2

権藤氏のことを知らない人もいるかと思うんで、Wikipediaへの
リンクを貼っておく:

http://ja.wikipedia.org/wiki/%E6%A8%A9%E8%97%A4%E5%8D%9A

(以下略)


優勝したときの監督ということもあって、権藤さんには非常にいい印象を持ってます でも実は就任したときはちょっと疑ってました(^^;) 大矢さんにもっとやらせろよとか (2位だったし)。

権藤博 - Wikipedia

権藤が監督を務めている間、大活躍を見せたロバート・ローズに「最高のボス」と慕われている。
ローズは毎年のように自分に取って代わる外国人を獲得したり、年俸を渋ったりする横浜フロン
トにわだかまりを持ち、あわよくば引退も考えていた。1999年の夏頃、権藤は球団の通訳ではな
く英語を話せる自分の娘のみを同伴させて1対1でローズと腹の割った話をした。結果「権藤が監
督でいる間は引退を考えないようにするよ」と権藤に全幅の信頼を置き、大活躍の下地を作った。

このエピソードは知らなかった。って「あわよくば」ってここで使うのはおかしくないかい?

権藤博 - Wikipedia

横浜監督就任時の野手陣はいわゆる「マシンガン打線」の絶頂期であり、投手の起用法さえしっ
かりしておけば、細かなサインプレーをせずとも得点を重ね勝利する力はあった。しかし前述の
放任主義・審判絶対主義的スタイルは時を経るごとにチーム内での軋轢を生み、特に野手陣との
亀裂が深まって行く。その象徴的な出来事として、2000年6月18日の対広島12回戦で、相手の右
投手ネイサン・ミンチーに対し、左打者の駒田徳広に代えて右打者の中根仁を代打に送ったこと
で、プライドを傷つけられた駒田が試合中にもかかわらず帰宅するという造反事件が起きた[8]。
なお、駒田はこのシーズン終了後に現役を引退。一方の権藤も、当時球団社長の大堀隆とは兄弟
のように蜜月だったが、他のフロント陣との対立も相俟って同年限りで退任した。

断片的な情報しか知らないけど、 放任主義の監督じゃやってられないって「連れてこさせた」森さんの時代にまた… なんだよなあ。

■_ radix sort

stackoverflow から

optimization - Optimizing radix sort in Haskell - Stack Overflow

I'm still learning Haskell and I wrote following radix sort function. It seems to work 
correctly, but the problem is that it is rather memory inefficient. If compiled with 
ghc, the memory goes highly over 500MB already with input list of size 10000 elements.

わたしはHaskellの勉強を続けていて、以下にあるような基数ソートを書いてみました。
正しく動いているようなのですが、メモリー面で非効率的なのが問題です。
ghc でコンパイルした場合、10000要素のリストの入力で500MBを遙かに超えるメモリーを
使ってしまいます。


So I want to ask you how could the following algorithm/code improved to make it more 
efficient in terms of speed and memory. What is the best place to start?

そこでお訊きしたいのは、以下で使っているアルゴリズムやコードをどのようにすれば
スピードやメモリーの点においてより効率の良いものにできるのかということです。
どこから始めるのが最善でしょうか?

import System.Random

-- radixsort for positive integers. uses 10 buckets
radixsort :: [Int] -> [Int]
radixsort [] = []
radixsort xs =
    -- given the data, get the number of passes that are required for sorting
    -- the largest integer
    let maxPos = floor ((log (fromIntegral (foldl max 0 xs)) / log 10) + 1)

        -- start sorting from digit on position 0 (lowest position) to position 'maxPos'
        radixsort' ys pos
         | pos < 0   = ys
         | otherwise = let sortedYs   = radixsort' ys (pos - 1)
                           newBuckets = radixsort'' sortedYs [[] | i <- [1..10]] pos
                       in  [element | bucket <- newBuckets, element <- bucket]

        -- given empty buckets, digit position and list, sort the values into
        -- buckets
        radixsort'' []     buckets _   = buckets
        radixsort'' (y:ys) buckets pos =
            let digit = div (mod y (10 ^ (pos + 1))) (10 ^ pos)
                (bucketsBegin, bucketsEnd) = splitAt digit buckets
                bucket = head bucketsEnd
                newBucket = bucket ++ [y]
            in radixsort'' ys (bucketsBegin ++ [newBucket] ++ (tail bucketsEnd)) pos
    in radixsort' xs maxPos

-- get an random array given an seed
getRandIntArray :: Int -> [Int] 
getRandIntArray seed = (randomRs (0, div (maxBound :: Int) 2) (mkStdGen seed))

main = do
        value <- (\x -> return x ) (length (radixsort (take 10000 (getRandIntArray 0))))
        print value

Have you considered using arrays from the IO monad?


Thanks, I'll definitely check out other data types as soon as I feel more comfortable 
with Haskell basics. 

The main problem is your function radixsort'', because ++ is O(n^2) and it copies each 
time the list given as the first argument.

pack (-1) r' _ = r'
pack n  r' relems =
    let getn = (map snd) . (filter ((n==) . fst))
    in pack (n - 1) ((getn relems):r') relems
radixsort'' elems pos = 
    let digit = \y -> div (mod y (10 ^ (pos + 1))) (10 ^ pos)
        relems = zip (map digit elems) elems
    in pack 9 [] relems


謎めいている…○| ̄|_

■_ typedef

gaucheのIRCで興味深い話をされていたので。

Gauche > Archives > 2011/03/12
2011/03/10 19:33:44 PSTrokujyouhitoma
#
はじめまして。
#
c-wrapperを使ってPython.hを読み込む際のエラーに悩まされています。
#
実行コード:
#

(use c-wrapper)
(c-load-library "libpython2.6.so")
(c-include "python2.6/Python.h")

#

/usr/include/python2.6/cobject.h:56:     void (*destructor)(void *);
/usr/include/python2.6/cobject.h:56: syntax error (at token: RPAREN)
*** ERROR: syntax error
Stack Trace:

#

0  (with-error-handler (lambda (e) (let ((e e)) (%guard-rec e e (else ...
	[unknown location]
  1  (with-error-handler (lambda (e) (let ((e e)) (%guard-rec e e (else ...
	[unknown location]
  2  (#:loop460 (cddr #:args459) #:G461)
        [unknown location]
  3  (parse-source include-dirs headers options)
        At line 1158 of "/usr/local/share/gauche-0.9/site/lib/c-wrapper/c-parser.scm"
  4  (with-error-handler (lambda (e) (let ((e e)) (%guard-rec e e (else ...
        [unknown location]

#

5  (c-parse (if (list? include-dirs) include-dirs (list include-dirs) ...
        At line 105 of "/usr/local/share/gauche-0.9/site/lib/c-wrapper.scm"
  6  (read-eval-print-loop (lambda () (rl-set-prompt-state! 'ps1) (read ...
        At line 44 of "/usr/local/bin/gosh-rl"

#
助言いただければ幸いです。

2011/03/10 19:44:09 PSTrokujyouhitoma
#
環境は、Fedora11, Gauche0.9.1 [utf-8,pthreads], x86_64-unknown-linux-gnuです。

2011/03/11 15:09:14 PSTkoguro
#
> rokujyouhitoma
#
エラーの原因ですが、object.h で typedef void (*destructor)(PyObject *); としている箇所
があって、destructor を 型の名前(TYPENAME)とc-wrapperが認識したためにシンタックスエラ
ーが発生しました。
#
うまい解決法がすぐに思いつかないのですが、どうしても使いたいという場合は、Python のヘ
ッダファイルを一式コピーした上で、cobject.h 56行目の void (*destructor)(void *); の
destructorを別の名前に変更すると使えるようになると思います。ざっとgrepしてみたところ、
ヘッダファイル内では PyCObject の destructor をその名前で参照している箇所はなさそうな
ので。
#
さすがにad-hoc にルールを追加しただけじゃ、reduce/reduce conflict が発生するなあ。
2011/03/11 15:33:57 PSTkoguro
#
そうだlexerにad-hocな修正を入れれば一応使えるんだ。
#

--- src/c-lex.c (revision 664)
+++ src/c-lex.c (working copy)
@@ -725,6 +725,8 @@
         SCM_RETURN(Scm_Cons(SYM(U_identifier), sym));
     } else if (SCM_EQ(last_token, SYM(U_struct)) || SCM_EQ(last_token, SYM(U_union))) {
         SCM_RETURN(Scm_Cons(SYM(U_identifier), sym));
+    } else if (SCM_EQ(last_token, SCM_INTERN("*"))) {
+        SCM_RETURN(Scm_Cons(SYM(U_identifier), sym));
     } else if (SCM_EQ(last_token, SYM(U_at_interface))) {
         install_type(sym);
         SCM_RETURN(Scm_Cons(SYM(U_identifier), sym));

#
これでとりあえずは通ると思います。
#
typedefの取り扱いは難しいなあ。
2011/03/11 20:05:39 PSTshiro
#
構造体のメンバ名がtypedef名をシャドウしてるって感じになってるのかな?
2011/03/11 20:15:51 PSTkoguro
#
そうです。C言語の規約的に正しいのかどうかはわかりませんが。
#
lexerの段階でIDENTIFIERかTYPENAMEかを判別しなくちゃならないんですが、たまに同じ名前が使われるんですよね。
2011/03/11 20:21:30 PSTshiro
#
lexerがその意味でstatefulになるってのは昔Cの処理系いじってた時に苦労した覚えが。苦労と
いうか、綺麗に書けないからいやな感じ。

知らなかった…修行が足りん○| ̄|_

■_ 素数を…

俺もやってたのにという方はごめんなさい

Twitter / @yhara (Yutaka HARA): 素数を数えて落ち着きたいプログラマのためのワンライナ ...

素数を数えて落ち着きたいプログラマのためのワンライナ(Ruby 1.8/1.9)

$ ruby -e 'require "mathn"; Prime.new.each{|x| p x; sleep 1.5}'
Twitter / @shinichiro hamaji: @yhara 好きなイディオムを使ってあまり素数数え ...

@yhara 好きなイディオムを使ってあまり素数数えてなさそうな見た目のを…

ruby -e '("p"*999).scan(/p/){(p$&.size;sleep 1.5)if/^(?!(pp+)\1+$)pp+/=~$`}'

Twitter / @Kazuhiro Inaba: 素数を数えるプログラム、面白いのが全然思いつかない。 ...

素数を数えるプログラム、面白いのが全然思いつかない。うーん

(1..23**45).inject{|*x|x[1,x.inject(&:%)].inject(method(:p),&:[]);x.inject(2,&:*)}
素数を数えて寝る - jarp,

s=q=1;loop{q+=1while 1>s%q*s*=q;p q;sleep 1.5} 

■_

2011年03月12日

■_

いろいろ書くネタは集めてそれなりにまとめてたんですが、 明日以降ということで。

■_

■_ Python's list implementation

面白い。 Python's list implementation | Laurent Luce's Blog

訳して紹介。と行きたいけど図入りは面倒なのよ…

2011年03月11日

■_

無事です。 鉄道が全滅で(深夜にかけて少しずつ動きましたが)、 会社から自宅まで3時間弱歩いて帰りました。 色々思うところがありますが、今日のところはこれで。

■_

■_


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

ホームへ


リンクはご自由にどうぞ

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