Nov 16, 2008

I Moved this blog

I move into WordPress from Blogger.

Protean [Henggen-Zizhai]

Nov 14, 2008

Difference between "do end" and "{ }" in Ruby

"{ }" has a stronger connection than "do end".


def foobar a, b
if block_given?
yield a, b
else
puts a * b
end
end



foobar is called with block.


foobar 2, 3 do |a, b|
puts a + b #=> 5
end



b is called with block.


def b
yield
end

foobar 2, b { 3 } #=> 6

Nov 13, 2008

Birthday Party

Today is my niece's birthday.
We're going to meet her.

Nov 12, 2008

Great Help of Vim

Type ":help!" when you get panick.

Sep 3, 2008

A Google Chrome's tab is on a process.

I tried this on a tab.

<html>
<body>
<button onclick="alert('not freese');">check</button>
<button onclick="for (var i = 0; ; i++) { };">freeze</button>
</body>
</html>


The tab froze.
But other tabs didn't freeze.


Then I tried this.

<html>
<body>
<button onclick="alert('not freese');">check</button>
<button onclick="for (var i = 0; ; i++) { alert(i); };">freeze</button>
</body>
</html>


Google Chrome can stop this script.
IE, Firefox and Safari can't stop this.

Aug 30, 2008

Help me! (JavaScript)

Regular expression.

<html>
<body>
<pre style="color:blue">
target
</pre>
<script type="text/javascript">
var m = document.body.innerHTML.match(/<pre[\w\s:;="]*>((.|\n)*)<\/pre>/g);
alert(m);
</script>
</body>
</html>

Firefox and Safari are OK.
But IE6 and IE7 are NG.
Why?

Aug 27, 2008

Boot Up Yourself with Ruby

I'm reading a book written about Ruby.
It's for biginers and easy to read.

Aug 22, 2008

Radiant CMS

I use Radiant CMS.
It's made of Ruby on Rails.

http://radiantcms.org/

It's difficult to use it.
I want some functions such as preview and file uploading.

Aug 17, 2008

You Can Do

You can do only what you can do.

Aug 13, 2008

Programming Less

I don't write codes these days.
Am I a programmer?

Aug 10, 2008

I study English.

I study English.
I want to read overseas web sites.

Aug 4, 2008

Sell Teaching Methods

A comment for Rich Dad.
Starting a teaching service is one way to get an income. Do you have any other ideas that will increase your income stream?
I think that teaching methods can be sold.

Jul 29, 2008

Rich Dad

I want to be a Rich Dad.

I read Robert Kiyosaki's "Rich Dad, Poor Dad" again today.
I should start my own business.

Jul 27, 2008

Boot Camp

I tried Boot Camp of Leopard.
I installed Windows XP.

It's very messy to reboot for switching Leopard and Windows.
I want VMware Fusion.

Jul 26, 2008

Redmine

I decided to use Redmine for project management.
It's made by Ruby on Rails.
It can work with Subversion.

Jul 24, 2008

MS Paint Like Software

PaintBrush is a MS Paint like software which can be used Mac.

Paintbrush: The Bitmap Image Editor for Mac OS X

It's very simple and easy to use.

Jul 21, 2008

Firefox Add-ons

I want to make some Firefox add-ons.
I want to make some Greasemonkey scripts.

But I have no idea.

Jul 19, 2008

Trouble of the Time Machine

Something goes wrong with Time Machine when my MacBook resumes from the sleep mode.
What is the cause of it?

Jul 18, 2008

Mac User

I became a Mac user.
I used Windows for desktop and Linux for server.
I had not used Mac.

It is difficult to use Mac before I use to be it.

Jul 10, 2008

MacBook, MacBook

I'm looking forward to get a MacBook.
Can I get it next week?

Jul 7, 2008

MacBook

I orderd a MacBook.
I get it after a few weeks.

Jul 6, 2008

People Can't Live Alone.

People can't live alone.
Someone is supported by anyone.

Jun 29, 2008

No Time

I have no time to read books.
I have no time to read mails.
I have no time to read RSS feeds.

I should learn time management.

Jun 28, 2008

Busy!

I'm busy.
I'm creating two web site.

Jun 26, 2008

Next Action

It is important to clearly image the Next Action.
Think what is the Next Action.

Jun 25, 2008

Validation of Rails

The validation function of Rails is very convenient.

When errors occur, textboxes are bounded by "div" tags.
Instead of "div", I want to use "span".

I write a code in config/environment.rb.
ActionView::Base.field_error_proc = Proc.new{ |html_tag, instance| "#{html_tag}" }
Complete!

Jun 24, 2008

Reading Books

We should read more books.
Book brings up us.

Jun 22, 2008

Hair Cut

I must have my hair cut.
I'm told that I ware a "helmet".

Jun 21, 2008

Watching TV With a Cell Phone

In Japan, it is popular to watch TV with a cell phone.
I bought new cell phone which display is high quality.

Jun 18, 2008

iPhone

iPhone is sold in Japan.
Someone says that the sales of iPhone is not well because Japanese cell phones have high-spec.
I think so.

Jun 17, 2008

Out of the Hospital

My wife and daughter was out of the hosital.
It is hard for me to care of them.

Jun 15, 2008

Never Give UP!

Never Give UP!!!!
I'll fight!!!!

Jun 13, 2008

Clinic

I'm tired because I took my daughters to a clinic.
I must take them tomorrow again.

Jun 11, 2008

Touch

I touched my baby who was born yesterday.
She is in NICU.

Jun 10, 2008

Birth!

My 3rd daughter was born today!
She looked so fine.

Jun 9, 2008

A High Fever

My daughter has a high fever.
She looks painful.
I was worried.

Jun 8, 2008

Coaching Session

I experience coaching tonight.
I'm looking forward to it.

Jun 7, 2008

Library

Today I worked at Kumamoto University's Library.
There was no student who used PC.
And there are few books about IT.
I thought Kumamoto is not advance about IT.

Jun 6, 2008

Cycling

We have two cars.
Today my father and my brother used them.
Then I couldn't use the car.
So I used my bicycle.
I'm very tired because I rode it for a long time.

Jun 5, 2008

091-100

In Japan, programmers have difficulty getting promoted or returning to their jobs after taking a long off.
In the U.S, do parents drive their children everywhere until they are old enough to get a driver's license?
"Excuse me. Could you tell me how to get to the dream?" "Go straight!"
"What do you think of our new boss?" "There is something about him that attracts me."
People who don't feel guilty about writing spaghetti codes really make me angry.
Everyone is born with a talent. The question is whether they can find it or not.
When I log in Twitter, I ran into an old friend from high school.
This code is worth reading to over and over again. I recommend it.
Unit test play an important part in your development. If you don't want to make bugs, you should do a unit test.
Bear in mind that if you have enthusiasm, you can succeed in anything.

Jun 4, 2008

081-090

Size of tab indent vary from programming language to language. In Ruby, 2 characters space is more common than 4 characters.
Kumamoto is located center of Kyushu.
Quite a few elderly programmer look down on their subordinates, who cannot do anything by themselves ask too much of them.
The data center is about twenty minutes' walk from here, but it takes only five minutes to get there by subway.
It cost 180,000 yen to buy this PC.
There are seven people in my family. Our house is near a big park. The
tendency for geeks to try everything that is new is usual.
When I was studying in Kumamoto, a famous professor taught us.
Tom finally realized his dream of becoming a super hacker, but at the expense of many other things.
If programmer life gives you stress and fatigue, it is best to relax in the mountains of Aso in order to relieve them.

May 30, 2008

071-080

However many programs you write, it's not for you unless you test them.
Although you believe you know a word, you may learn something new if you look it up in the Wikipedia.
Some programmers lack common sense and write a lot of magic numbers.
In order to stay healthy, you should sleep well and enjoy your life.
If you work in a venture company for a while you have an opportunity to look at your life from a different point of view.
It is not until you go abroad that you realize how wide the world is.
It is a pity that many Japanese programmers mistakenly believe that they have only to speak English to be internationally-minded.
It is surprising that many programmers don't care how beautiful codes you write as long as they can run.
The best things you can write beautiful codes are to refactor them.
It is said that three out of ten programmers don't do unit tests.

May 29, 2008

061-070

Professional combat sports is far more exciting at a ring side than on TV.
The fee of this web site is about twice as expensive in Japan as in the U.S.
Just because young people today read less than they used to, it doesn't always follow that they are less eager to learn.
Frankly speaking, the source code of Linux I read yesterday were far more difficult than I had expected.
A lot of people write blogs, but very few of them continue to update.
A lot of users complain that the software is difficult to use.
In some companies programmer have too much task, while in others they are free.
Don't forget to turn off the PC before you leave your desk.
There is a saying that a spaghetti program can cause bags. Take care not to write it.
On facebook, you can exchange thoughts and ideas with people all over the world, regardless of their age, sex, or nationality.

May 28, 2008

041-050

Tom has a nice keybord, and he never lets anyone else play them.
At first I thought Tom was boasting, but later I realized it was truth.
Last Sunday I tried making a Java application for the first time, and it was difficult.
Some programmer say that they don't like summer because it is so hot that they don't feel like writing any codes. However, I like the heat of summer because I can program in the pool.
James came to Japan eight years ago not only because of sightseeing, but also because he wanted to a programming seminar.
I am against water-fall process. That is because it would cost many time to review.
The graph shows that in Japan the programmers rate has been decreasing. This decrease is partly because the work of programmers is very hard.
I apologized to Ann for writing spaghetti code, but she didn't forgive me.
During the work, my PC bean to beep, and the boss severely scolded me. I regretted that I continued pushing the shift key.
It's so busy developing the application every day that I have no time to read o'reilly books.

May 26, 2008

051-060

This code is too difficult for me to understand alone.
While traveling in Oita, I was disappointed that wherever I went, there was no people.
I was very happy when I saw my wife going to shopping wearing the dress I had bought her.
If you expect that programmers only face to PC, then this proves that you don't understand what programmers are.
Most Japanese system engineers spend most of their time working to live.
Many programmers usually express their feelings in IRC.
Whether a programmer is good or bad depends not only on how many books he has and how good they are. It also depends on how intelligent he is.
The increase in the amount of bugs in the program is closely connected with programmer's motivation.
The more modern civilization advances, the longer we are forced to stay up at night and the less sleep we get.
Programmers and authors are alike in that both of them write something.

May 25, 2008

031-040

I don't finish making the web application I've made for a week, so now I have no time.
If you had used this library, you would probably have finished in one day.
My wife says that we should go to the bank because if we don't go, we might run short of money.
I wish I could have a lot of money. However, if this wish came true, I would become to a sloth.
My wife looks happy. Something good must have happened to her.
If you have been to Kumamoto Castle, you must have been impressed by the beautiful stone wall.
Without the Internet, the history of the 21th century would have been completely different.
Some programmers coming to the office act as if they are at home.
When I was an employee, I often wished my salary were a little more.
I'd like to work as a volunteer helping beginner of personal computers.

May 24, 2008

021-030

It has been over 5 years since I began programming, but I have many things to learn.
When I went to bed yesterday night, I couldn't find my pillow.
I'm wearing glasses now, but I can't make out what the program says.
Less than thirty minutes after I start debugging, I start to feel tired.
Humans learn to express what they think by the age of five or six.
Thanks to the program you wrote me the other day, I managed to build up this software.
This program had changed a lot, so when I saw it at a debug phase, I didn't recognize it.
Last week I took two days off, but went on a trip nowhere.
When I visited my collage for the first time in five years, I found that it was what it used to be.
I stayed up till eleven last night giving my daughter milk, so I feel very sleepy.

May 23, 2008

011-020

It never occurred to me that my code might bring about a serious bug.
"Tom, the server is ready." "OK, Jim. I'm coming."
I'll tell you when I find bugs.
If you take the bus to the data center from here, you have to change two times.
I've decided to become a programmer when I graduate from college.
This code doesn't work. Something seems to be wrong with it.
The best thing about working with an Italian programmer was that he made spaghetti for me.
I lived in Oita for four years when I was in my teens because my father was transferred there.
Ruby on Rails is widely used, so Ruby has been getting a lot of visibility over the last few years.
I've often heard Tom boast that he is very good at programming, but I've never actually seen him program.

May 22, 2008

001-010

It would be dangerous to drink seven cups of coffee and write program.
It is very dangerous to release a software before the test case turns green.
It is really pleasant to program early in the morning, listening to Mozart.
Most Japanese programmer don't go to a programming school to prepare for company entrance exams.
When waiting for the build process to finish, most Programmer become irritated in only one minute.
An elderly programmer sitting next to me at office asked me where i was going.
A programmer told us that we should use Wiki to share knowledge because paper was inconvenient.
Everyone should be free to decide which programming language to use.
It is impossible to predict where and when there will be a serious bug.
My colleague insisted that everything would be all right, but I couldn't help feeling worried.

May 21, 2008

Google Docs Offline

I have just found it!
Google Docs can be used offline.
It uses Google Gears.

May 20, 2008

Japanese Facebook

Facebook Japanese Edition was released.
I wonder if it gets many users.
There are not less people who don't like to use real name on web.

May 19, 2008

Many Things To Do

I have many things to do.
I want to study English for recreation.
I feel good while studying and programing.

May 18, 2008

Rails2.0 Migration File

The format of Rails2.0 migration file from Rails 1.2.
An example of Rails2.0:

def self.up
create_table :user do |t|
t.string :name, :address
t.timestamps
end
end

"created_at" and "updated_at" are automatically made when "timestamps" is written.

May 17, 2008

DIV to SPAN

environment.rb

ActionView::Base.field_error_proc = Proc.new { |html_tag, instance| "<span class=\"fieldWithErrors\">#{html_tag}</span>" }

May 16, 2008

Rails 1.2 or 2.0 ?

Which version should I use, Rails 1.2 or 2.0?
I want to try 2.0.
But some plugins can't be use and there are few documents.

May 15, 2008

Google in Japan

Most Japanese people use Yahoo! when they search something.
There are many people who don't know Google.

May 14, 2008

Reduce Functions

I make a web site.
At first, I had added functions.
But I realize it is more important to reduce functions.
I make a simple web site.

May 13, 2008

Change the World

If you change, the world changes.

May 12, 2008

Moonlight

Moonlight is Silverlight for Linux.
Moonlight has a feature that Silverlight doesn't have.
It work out of browsers.
I'm looking forward to its release.

May 11, 2008

PRIDE

I prise my pride.

May 10, 2008

Shinichi Hoshi

Shinichi Hoshi - Wikipedia, the free encyclopedia
Shinichi Hoshi was a Japanese novelist and science fiction writer. He is best known for his "short-short" science-fiction stories, often no more than three or four pages, of which he wrote over 1000.
His stories are very fun.
I recommend them.

May 9, 2008

The Matrix

I want to watch "The Matrix".
Is it fun?

May 7, 2008

Give up. You can't win.

Our cat stole my favorite pen.
So I threatened him.
"Give up. You can't win."

May 6, 2008

1 + 1 = 3

Ruby.
Classes are open.
class Fixnum
def + x
- (- self - x - 1)
end
end

p 1 + 1

C#...

static class Program
{
static void Main(string[] args)
{
Console.WriteLine("1 + 1 = {0}", 1 + 1);
Console.ReadLine();
}
}

public class Console
{
public static void WriteLine(string format, object arg0)
{
if (arg0 is int)
{
arg0 = (int)arg0 + 1;
}

System.Console.WriteLine(format, arg0);
}

public static string ReadLine()
{
return System.Console.ReadLine();
}
}

May 5, 2008

Action Log

I began to log my daily action.
It's useful for reducing wasting time.

May 4, 2008

May 3, 2008

Library

I went to the library.
There were many books to read.
I want to be a fast-reader.

May 2, 2008

Coaching

I'm interested in coaching.
I want to experience coaching.
And I want to read books about coaching.

May 1, 2008

iPod touch Jailbreak

Firmware is 1.1.4.
I used ZIPhone.
It's very easy.
My iPod touch became more useful.

Apr 30, 2008

Mistake

I made a mistake.
I lost much money...

Apr 29, 2008

HotRuby

HotRuby - Ruby on JavaScript & Flash


def fib(n)
n <= 2 ? 1 : fib(n - 1) + fib(n - 2)
end

puts fib(10)

Apr 27, 2008

Shogi Game

I download a Shogi game in my cellular phone.
I can' t win.
I want to be good at Shogi.

Apr 26, 2008

FON

I take part in FON network.
I ordered a rooter.
It's time to use iPod touch Wi-Fi.

Apr 25, 2008

Moonlight

Moonlight - Mono



A page to track the various projects that make up the Mono-based implementation of Silverlight.


The goals are:


  • To run Silverlight applications on Linux.

  • To provide a Linux SDK to build Silverlight applications.

  • To reuse the Silverlight engine we have built for desktop applications.

To reuse the Silverlight engine we have built for desktop applications!!!!

I'm looking forward to the Release of Moonlight.

Apr 24, 2008

Dynamic Scaffolding on Rails 2.0

A sample code of dynamic scaffolding.

class SampleController < ApplicationController
scaffold :person
end


Dynamic scaffolding is removed in Raisl 2.0.
You need to install as a plugin.


% script/plugin install scaffolding
% script/plugin install http://tools.assembla.com/svn/breakout/breakout/vendor/plugins/classic_pagination/
% script/plugin install http://tools.assembla.com/svn/breakout/breakout/vendor/plugins/will_paginate/


You can use "script/generate scaffold" without the plugin.

Apr 23, 2008

I want to program.

I have not written program for 2 months.
I want to program.
But I have something to do.
I want to begin my own business.

Apr 22, 2008

Passenger (mod_ruby for Apache)

I tried Passenger (mod_ruby for Apache).
Overview — Phusion Passenger (a.k.a. mod_rails)

It's easy to install with RubyGems.
Radiant CMS is running on mod_ruby.
It's fast.

Apr 21, 2008

TOEIC

I want to try TOEIC, an English exam.
Japanese and Korean people love TOEIC.
Why?
I think TOEFUL is more popular in the world.

Apr 20, 2008

A Book About NLP

I bought a book writen about NLP.
It's writen in English.
Am I able to read it?
I challenge!

Apr 19, 2008

Why do I work?

Working for money isn't important for me.
Why do I work?
What do I do?
I wish that the world is peaceful and people are happy.

Apr 18, 2008

XOOPS

I installed XOOPS.
It's a most popular CMS in Japan.

Apr 17, 2008

Radiant CMS

I installed Radiant CMS used in Ruby official site.
I used MySQL for database.
It took a long time to install.
I'm tired.

Apr 16, 2008

Scheduling Management System

My schedule management system is iPod touch.
Unfortunately, iPhone isn't released in Japan.

Apr 15, 2008

CentOS

I installed CentOS for my server.

I mistook DNS configuration.
I wrote wrong IP address.

Be careful!

Apr 14, 2008

Social Entrepreneur

I'm interested in "Social Entrepreneur".

Apr 13, 2008

Server Setup.

I setup a server tomorrow.
I must be careful about security.

Apr 11, 2008

I'm going to begin Shogi.

I'm going to begin Shogi.
Shogi is a Japanese board game played by two players.
I think that it is similar to chess.

Apr 10, 2008

I fight.

I fight with the utmost energy.
Tomorrow's myself isn't the same as today's myself.

Apr 9, 2008

Mie is a cat.

Mie is a cat.
He and I share a room.

I was scratched by him.
He jump on my server.

Apr 8, 2008

I have got a EeePC.

I have got a EeePC.
I'm going to install eeeXbuntu that is localized to Japanese.
I want a 16GB SDHC memory card.

Apr 7, 2008

I'm learning Linux.

I'm learning Linux.
Which distribution do you like?
I'm going to use Ubuntu for desktop and CentOS for server.

Apr 6, 2008

I ordered EeePC.

I ordered EeePC.

Windows XP is pre-installed in Japanese Edition.
And 4GB SDHC memory card is added.

I'll install Ubuntu.

Apr 5, 2008

How to send mail via Yahoo!Mail by Ruby.

How to send mail via Yahoo!Mail by Ruby.
Yahoo!Mail use POP before SMTP.

A sample code.

require 'net/smtp'
require 'net/pop'
require 'time'

content = <<EOF
From: from@yahoo.co.jp
To: to@yahoo.co.jp
Subject: Hello!
Date: #{Time.now.rfc2822}

How are you.
EOF

Net::POP3.start('pop.mail.yahoo.co.jp', 110, 'Yahoo! ID', 'password') do |pop|
end

Net::SMTP.start('smtp.mail.yahoo.co.jp', 25, 'yahoo.co.jp', 'Yahoo! ID', 'password', :login) do |smtp|
smtp.send_message(content, 'from@yahoo.co.jp', 'to@gmail.com')
end

Apr 4, 2008

How to send mail via Gmail by Ruby.

How to send mail via Gmail by Ruby.
Gmail use TLS that isn't supported by Ruby 1.8.
You can use tlsmail.


# gem install tlsmail


A sample code.

require 'tlsmail'
require 'time'

content = <<EOF
From: from@gmail.com
To: to@gmail.com
Subject: Hello!
Date: #{Time.now.rfc2822}

How are you.
EOF

Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
Net::SMTP.start('smtp.gmail.com', 587, 'gmail.com', 'from@gmail.com', 'password', :login) do |smtp|
smtp.send_message(content, 'from@gmail.com', 'to@gmail.com')
end

This code don't work in Ruby 1.8.3.

Apr 3, 2008

Check your IP address.

You can get your IP address.

http://tech.upper.jp/remote_addr/

This script use cgi.remote_addr in Ruby.

Apr 2, 2008

net/smtp of Ruby 1.9

It's possible to use SSL/TLS with net/smtp of Ruby 1.9.

Apr 1, 2008

"Grammar in Use Intermediate"

I decided to study grammar of English with "Grammar in Use Intermediate".
I expect progress of this blog.

Mar 31, 2008

ERB

I'm making a CGI program with Ruby.
I use ERB.
It's possible to write PHP-like markup.
If you use Ruby on Rails, ERB is used in views.

Mar 30, 2008

First programming in a long time.

I'm making a CGI program for posting messages.
I use Ruby.
But I don't use Ruby on Rails because of its bad performance.

Mar 29, 2008

What is the first program?

What is the first program for beginners?

"Hello, world!"?
Is it fun?

If they use C# or VB.NET, Windows application is better.
If they use Ruby (Ruby on Rails), Web application is better.

Mar 28, 2008

No excuse! No excuse!

No excuse! No excuse!

Everything is brought about by me.

No excuse! No excuse!

Mar 22, 2008

SICP Exercise 1.22

A procedure that checks a prime number.

(define (prime? n)
(= n (smallest-divisor n)))
(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (+ test-divisor 1)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (square n)
(* n n))


A procedure that measures the time for "prime?".
I rewrite a bit.

(define (timed-prime-test n)
(newline)
(display n)
(start-prime-test n (runtime)))
(define (start-prime-test n start-time)
(if (prime? n)
(report-prime (- (runtime) start-time))
#f))
(define (report-prime elapsed-time)
(display " *** ")
(display elapsed-time)
#t)


DrScheme doesn't have "runtime".

(define (runtime)
(current-milliseconds))


My answer.

(define (search-for-primes min max cnt)
(cond ((> min max))
((= cnt 3))
((even? min) (search-for-primes (+ min 1) max cnt))
(else
(if (timed-prime-test min)
(search-for-primes (+ min 2) max (+ cnt 1))
(search-for-primes (+ min 2) max cnt)))))



(search-for-primes 1000 9999 0)
(search-for-primes 10000 99999 0)
(search-for-primes 100000 999999 0)
(search-for-primes 1000000 9999999 0)


It's impossible to measure the time.

Mar 20, 2008

SICP Exercise 1.21


(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (+ test-divisor 1)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (square n)
(* n n))



(smallest-divisor 199)
(smallest-divisor 1999)
(smallest-divisor 19999)



199
1999
7

Mar 19, 2008

SICP Exercise 1.17 - 1.18

A multiplication procedure.

(define (* a b)
(if (= b 0)
0
(+ a (* a (- b 1)))))


Exercise 1.17.
Rewrite to a code that uses a logarithmic number of steps.
(Use "double" and "halve".)

(define (* a b)
(cond ((= b 0) 0)
((even? b) (* (double a) (halve b)))
(else (+ a (* a (- b 1))))))

(define (double n)
(+ n n))

(define (halve n)
(/ n 2))


Exercise 1.18.
Rewrite to a code that generates an iterative process.

(define (* a b)
(*-iter a b 0))

(define (*-iter a b n)
(cond ((= b 0) n)
((even? b) (*-iter a (halve b) (double n)))
(else (*-iter a (- b 1) (+ n a)))))

(define (double n)
(+ n n))

(define (halve n)
(/ n 2))

Mar 18, 2008

There will be an answer.

Japanese Programmer's: From recursion to iteration.

I found an answer.

(define (fast-expt2 b n)
(fast-expt-iter 1 b n))

(define (fast-expt-iter a b n)
(cond ((= n 0) a)
((even? n) (fast-expt-iter a (square b) (/ n 2)))
(else (fast-expt-iter (* a b) b (- n 1)))))

Mar 17, 2008

From recursion to iteration.

Exercise 1.16 of 1.2.4 Exponentation in SICP.

Recursion.

(define (fast-expt b n)
(cond ((= n 0) 1)
((even? n) (square (fast-expt b (/ n 2))))
(else (* b (fast-expt b (- n 1))))))

(define (even? n)
(= (remainder n 2) 0))

(define (square n)
(* n n))


How do I rewrite this code to iterative process?

Mar 16, 2008

How to trace in DrScheme.

1. Choose language
[Choose Language] - [PLT] - [Textual (MzScheme, includes R5RS)]

2. Incrude a library

(require (lib "trace.ss"))


3. Trace

(trace fib)
(fib 10)

Mar 15, 2008

CPS : Continuation Passing Style

I write a code using recursion.

static int Fact(int n)
{
if (n == 0)
{
return 1;
}
else
{
return n * Fact(n - 1);
}
}


I write a code using CPS.

static int FactCPS(int n, Func cont)
{
if (n == 0)
{
return cont(1);
}
else
{
return FactCPS(n - 1, a => cont(n * a));
}
}

static int Fact(int n)
{
return FactCPS(n, a => a);
}

Mar 14, 2008

SICP Exercise 1.10.

Ackermann's function

(define (A x y)
(cond ((= y 0) 0)
((= x 0) (* 2 y))
((= y 1) 2)
(else (A (- x 1)
(A x (- y 1))))))



> (A 1 10)
1024
> (A 2 4)
65536
> (A 3 3)
65536

Mar 13, 2008

SICP Exercise 1.9.

A.

(define (+ a b)
(if (= a 0)
b
(inc (+ (dec a) b))))


B.

(define (+ a b)
(if (= a 0)
b
(+ (dec a) (inc b))))


A.

(+ 4 5)
(inc (+ (dec 4) 5))
(inc (inc (+ (dec 3) 5))))
(inc (inc (inc (+ (dec 2) 5))))
(inc (inc (inc (inc (+ (dec 1) 5)))))
(inc (inc (inc (inc 5))))
(inc (inc (inc 6)))
(inc (inc 7))
(inc 8)
9

This is a recursive process.

B.

(+ 4 5)
(+ (dec 4) (inc 5))
(+ (dec 3) (inc 6))
(+ (dec 2) (inc 7))
(+ (dec 1) (inc 8))
9

This is a iterative process.

Mar 12, 2008

Linear Recursion and Iteration Sample.

A linear recursion code.

(define (factorial n)
(if (= n 1)
1
(* n (factorial (- n 1)))))


A linear iteration code.

(define (factorial n)
(fact-iter 1 1 n))

(define (fact-iter product counter max-count)
(if (> counter max-count)
product
(fact-iter (* counter product)
(+ counter 1)
max-count)))

Mar 4, 2008

Micor thread with yield of C#.

Micro thread is called co-routine or fiber.
It is possible to implement micro thread by using yield.


class Program
{
static void Main(string[] args)
{
var microThread1 = MicroThread1();
var microThread2 = MicroThread2();
var microThread3 = MicroThread3();

Console.WriteLine("Begin");

microThread1.MoveNext();
microThread2.MoveNext();
microThread3.MoveNext();
microThread1.MoveNext();
microThread2.MoveNext();
microThread3.MoveNext();

Console.WriteLine("End");

Console.ReadLine();
}

static IEnumerator<object> MicroThread1()
{
Console.WriteLine("Mocro Thread 1-1");
yield return null;
Console.WriteLine("Mocro Thread 1-2");
yield return null;
Console.WriteLine("Mocro Thread 1-3");
yield return null;
}

static IEnumerator<object> MicroThread2()
{
Console.WriteLine("Mocro Thread 2-1");
yield return null;
Console.WriteLine("Mocro Thread 2-2");
yield return null;
Console.WriteLine("Mocro Thread 2-3");
yield return null;
}

static IEnumerator<object> MicroThread3()
{
Console.WriteLine("Mocro Thread 3-1");
yield return null;
Console.WriteLine("Mocro Thread 3-2");
yield return null;
Console.WriteLine("Mocro Thread 3-3");
yield return null;
}
}

Mar 3, 2008

I retire from my job.

I've finished the last work at office.
I start new life from tomorrow.

Mar 2, 2008

Programming School.

I want to make up a programming school.
Which programming language should I teach?

Mar 1, 2008

FizzBuzz Object (JavaScript)


<body>
<script type="text/javascript; version=1.7">
var fizzbuzz = {
case : [
{
cond : function(n) { return n % 15 == 0; },
proc : function(n) { return "FizzBuzz"; }
},
{
cond : function(n) { return n % 3 == 0; },
proc : function(n) { return "Fizz"; }
},
{
cond : function(n) { return n % 5 == 0; },
proc : function(n) { return "Buzz"; }
},
{
cond : function(n) { return true; },
proc : function(n) { return n + ""; }
}
],
convert : function(n) {
for (var i = 0; i < this.case.length; i++) {
if (this.case[i].cond(n)) {
return this.case[i].proc(n);
}
}
},
get : function(start, count) {
for (var i = start; i < start + count; i++) {
yield this.convert(i);
}
}
}

var ret = "";

for (var x in fizzbuzz.get(1, 100)) {
ret += x + " ";
}

document.body.innerHTML = ret;
</script>
</body>



  • It's possible to access fizzbuzz (this) while initializing of fizzbuzz.

  • It's possible to use yield keyword in anonymous function.

Feb 29, 2008

FizzBuzz Object (C#)


class Program
{
static void Main(string[] args)
{
var fizzbuzz = new
{
Case = new[] {
new {
Cond = new Func<int, bool>(n => true),
Proc = new Func<int, string>(n => null)
}
},
Convert = new Func<int, string>(n => null),
Get = new Func<int, int, IEnumerable<string>>((start, count) => null)
};

fizzbuzz = new
{
Case = new[]
{
new {
Cond = new Func<int, bool>(n => n % 15 == 0),
Proc = new Func<int, string>(n => "FizzBuzz")
},
new {
Cond = new Func<int, bool>(n => n % 3 == 0),
Proc = new Func<int, string>(n => "Fizz")
},
new {
Cond = new Func<int, bool>(n => n % 5 == 0),
Proc = new Func<int, string>(n => "Buzz")
},
new {
Cond = new Func<int, bool>(n => true),
Proc = new Func<int, string>(n => n.ToString())
}
},
Convert = new Func<int, string>(n => fizzbuzz.Case.Where(c => c.Cond(n)).First().Proc(n)),
Get = new Func<int, int, IEnumerable<string>>((start, count) => Enumerable.Range(start, count).Select(n => fizzbuzz.Convert(n)))
};

foreach (var x in fizzbuzz.Get(1, 100))
{
Console.Write(x + " ");
}

Console.ReadLine();
}
}



  • It's impossible to access fizzbuzz while initializing of fizzbuzz.

  • It's regarded as same type when an anonymous types have same properties.

  • It's impossible to set lambda expression to a property of anonymous type.

  • It's impossible to use yield keyword in anonymous method.

Feb 28, 2008

"Nabeatsu of the World" program.

It becomes "Aho" if multiples of 3 or numbers including 3.

module Enumerable
def aho(&block)
self.map do |a|
if 100 <= a
a.to_s
elsif block.call(a)
a.to_aho
else
a.to_s
end
end
end
end

class Integer
def to_aho
fig1 = [ "", "iiiichi", "niiii", "saaaan", "siiii", "goooo", "rooooku", "siiiichi", "haaaachi", "kyuuuu" ]
fig10 = [ "", "", "ni", "san", "yon", "go", "roku", "nana", "hachi", "kyu" ]

if self < 10
fig1[self]
elsif 10 <= self
fig10[self / 10] + "-ju-" + fig1[self % 10]
else
n.to_s
end
end
end


(1..100).aho{|a| (a % 3 == 0) || a.to_s.include?("3") }.each{|a| printf("%s ", a) }

Feb 27, 2008

How to make an Expression Tree.

I want to make this lambda expression.

Func mean = (x, y) => ((x + y) / 2);

Console.WriteLine(mean(10, 20));


Use Expression class.

ParameterExpression x = Expression.Parameter(typeof(int), "x");
ParameterExpression y = Expression.Parameter(typeof(int), "y");

ConstantExpression two = Expression.Constant(2, typeof(int));

BinaryExpression add = Expression.Add(x, y);
BinaryExpression body = Expression.Divide(add, two);

Expression<Func<int, int, int>> meanExp =
Expression.Lambda<Func<int, int, int>>(
body,
new ParameterExpression[] { x, y });
Func<int, int, int> mean = meanExp.Compile();

Console.WriteLine(meanExp);
Console.WriteLine(mean(10, 20));

Feb 26, 2008

Lazy Evaluation of Haskell.

From Exercise 1.5 of SICP.

What the result is this Scheme code.

(define (p) (p))

(define (test x y)
(if (= x 0)
0
y))

(test 0 (p))

It's an infinite loop.

The case of Haskell.

p = p

test x y = case x of
0 -> 0
_ -> y

test 0 p

The result is zero.
This is Lazy Evaluation of Haskell.

Feb 25, 2008

Square Roots by Newton's Method.

Square Roots by Newton's Method.

(define (sqrt x)
(define (good-enough? guess)
(< (abs (- (square guess) x)) 0.001))
(define (improve guess)
(average guess (/ x guess)))
(define (sqrt-iter guess)
(if (good-enough? guess)
guess
(sqrt-iter (improve guess))))
(sqrt-iter 1.0))

"x" is a free variable in the internal definitions.It gets its value from the argument with which the enclosing procedure sqrt is called.This dicipline is called "lexical scoping".

Feb 24, 2008

The SDK of iPod touch.

When I get the SDK of iPod touch?
Which programming language can I use?

Feb 23, 2008

"yield" in JavaScript 1.7

It's possible to use "yield" keyword in JavaScript 1.7.
It requires to specify the version (1.7).

<body>
<script type="text/javascript; version=1.7">

var i = 0;
var gen = (function() { while(1) { yield i++; } })();
alert(gen.next()); // 0
alert(gen.next()); // 1
alert(gen.next()); // 2

</script>
</body>

Feb 22, 2008

Quick Sort (Haskell vs C#)

A function for Quick Sort.

C#

static int[] QuickSort(int[] a, int c)
{
if (a.Length == 0) return a;
if (c == 0) return a;

int p = a[0];

int l = 0;
int h = 0;
int[] lo = new int[a.Length];
int[] hi = new int[a.Length];

for (int i = 1; i < c; i++)
{
if (a[i] < p)
{
lo[l++] = a[i];
}
else
{
hi[h++] = a[i];
}
}

lo = QuickSort(lo, l);
lo[l++] = p;
hi = QuickSort(hi, h);
for (int i = 0; l < lo.Length; i++)
{
lo[l++] = hi[i];
}

return lo;
}

Too difficult.


Haskell

qsort [] = []
qsort (p:xs) = qsort lt ++ [p] ++ qsort gteq
where
lt = [x | x <- xs, x < p]
gteq = [x | x <- xs, x >= p]

Very simple.


C# with Enumerable

static IEnumerable QuickSort(IEnumerable a)
{
if (a.Count() == 0) return a;

int p = a.First();
var xs = a.Skip(1);
var lo = xs.Where(y => y < p);
var hi = xs.Where(y => y >= p);

return QuickSort(lo).Concat(new[] { p }).Concat(QuickSort(hi));
}

This code get close to Haskell's one.

Feb 21, 2008

How to generate a random number in Scheme.

I couldn't find a function that generates a random number.
Instead, I make that function using "".

I wont to get current time for a seed.
But I couldn't a function for it.


(define (rand seed)
(let ((x seed))
(lambda ()
(set! x (remainder (+ (* 13 x) 5) 24))
x)))



(define a (rand 1))

(display (a))
(newline)
(display (a))
(newline)
(display (a))
(newline)



18
23
16

Feb 20, 2008

Closure of Scheme.

The simplest closure sample of Scheme.


(define (f x)
(let ((y x))
(lambda ()
(set! y (+ y 1))
y)))




> (define a (f 1))
> (display (a))
2
> (display (a))
3
> (display (a))
4

Feb 19, 2008

Conditional branches of Haskell.

I'm studying Haskell.

Haskell has some conditional statements.

1. pattern matching

fact 0 = 1
fact n = n * fact (n-1)


2. guard

fact n | n==0 = 1
| otherwise = n * fact (n-1)


3. if

fact n = if n==0 then 1
else n * fact (n-1)


4. case

fact n = case n of
0 -> 1
_ -> n * fact (n-1)

Feb 18, 2008

I try Haskell.

I'll conduct study sessions at my office this week.
I learned the basics of Haskell for it.
It's interesting to be able to create an infinite list by delay evaluation.

Feb 17, 2008

Output Fibonacci number without recurrence.

It is possible to write a code for Fibonacci number without recurrence.
Alternatively the code include a loop.


def fib(n)
a, b, c = 0, 1, 0

n.times do
c = a
a = b
b += c
end

a
end

p fib(10)

Feb 16, 2008

Use closure for event handler.

This is a sample program.
A number displayed on a label increases when a button is clicked.


public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

this.button1.Click += new EventHandler(button1_Click);
}

int num = 0;

void button1_Click(object sender, EventArgs e)
{
this.label1.Text = num.ToString();
num++;
}
}


This code uses a member field "num".


I rewrite this code using closure.


public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

this.button1.Click += make_button1_Click(0);
}

EventHandler make_button1_Click(int num)
{
return delegate(object sender, EventArgs e)
{
this.label1.Text = num.ToString();
num++;
};
}
}


This code uses no member field.
Closure memorize the variable "num".

Feb 15, 2008

I tried F# programming.

F# code for Fibonacci number.

let fib n =
let rec fib_iter n a b =
match n with
| 0 -> a
| _ -> fib_iter (n - 1) b (a + b) in
fib_iter n 0 1;;

printfn "%d" (fib 10);;


F# code for a maximum value.

let lst = [3;1;4;1;5;9;2];;

let rec fmax l x =
match l with
| [] -> x
| lh::lt ->
fmax lt
(if x > lh then x
else lh);;

printfn "%d" (fmax lst 0);;


I feel that the expression of F# is more powerful than Scheme.

Feb 14, 2008

Lambda Expression for maximum value.

When I don't use Lambda Expression.

int[] list = { 3, 1, 4, 1, 5, 9, 2 };

int max = 0;

for (int i = 0; i < list.Length; i++)
{
if (max < list[i])
{
max = list[i];
}
}

Console.WriteLine(max);


When I use Lambda Expression.

int[] list = { 3, 1, 4, 1, 5, 9, 2 };

Func fmax = null;
fmax = (l, x, i) => (i == l.Length) ? x : fmax(l, (x > l[i]) ? x : l[i], i + 1);

Console.WriteLine(fmax(list, 0, 0));


I can write functional program with Lambda Expression.

Feb 13, 2008

C# derives from...

C# is C++++.
By the way, the code name of C# was COOL (C like Object Oriented Language).

Feb 12, 2008

(SICP) 1 Building Abstractions with Procedures

I'm trying to read "Structure and Interpretation of Computer Programs" (SICP).
Today, I read "1 Building Abstractions with Procedures".
It's be summarized as follows.
Programming in Lisp is great fun.

Feb 11, 2008

Foreword of SICP.

I'm trying to read "Structure and Interpretation of Computer Programs" (SICP).
Today, I read "Foreword".
It's described about programming, Lisp and so on.

Feb 10, 2008

The SICP Web Site.

We can read "Structure and Interpretation of Computer Programs" (SICP) on web.

Welcome to the SICP Web Site

I'll try to read it.
But I'm not good at English...

Feb 9, 2008

How to read web pages offline on iPhone/iPod touch.

You can read web pages on iPhone/iPod touch when you are offline.

Read Offline for iPhone/iPod touch

This is a bookmarklet.

It's very convenient to read web pages offline.

Feb 8, 2008

Prototype chain of JavaScrit.

Prototype chain is a inheritance system of JavaScript.
Prototype of sub class is instance of base class.


var Person = function() {};
Person.prototype = {
name : "hoge",
toString : function() {
window.alert(this.name);
}
};

var Programmer = function() {};
Programmer.prototype = new Person();

var shunsuk = new Programmer();
shunsuk.name = "shunsuk";
shunsuk.toString();

Feb 7, 2008

Closure of JavaScript and C#.

A closure is a function that is evaluated in an environment containing one or more bound variables.

JavaScript.

function closure(init) {
var cnt = init;

return function() {
return ++cnt;
}
}

var r = closure(10);

alert(r());
alert(r());
alert(r());



C#.

Func<int, Func<int>> closure = init =>
{
int cnt = init;
return () => ++cnt;
};

var r = closure(10);

Console.WriteLine(r());
Console.WriteLine(r());
Console.WriteLine(r());



Output.

11
12
13

Feb 6, 2008

16GB iPhone and 32GB iPod touch.

Macworld | Apple offers 16GB iPhone, 32GB iPod touch

Apple on Tuesday added new models of the iPhone and iPod touch with more storage capacity. The company is now offering a 16GB version of the iPhone for $499, and a 32GB version of the iPod touch for $499. Both new devices are available immediately.


New iPod touch is applied the software update.
It includes five applications and home customize.

Feb 5, 2008

Scheme program for prime numbers.

I wrote a Scheme program that make a list of prime numbers.


(define (prime)
(define (prime-loop n pr)
(define (p? i p)
(if (= (length p) 0)
#t
(if (= (remainder i (car p)) 0)
#f
(p? i (cdr p)))))
(if (<= n 1000)
(prime-loop (+ n 1)
(if (p? n pr)
(append pr (list n))
pr))
pr))
(prime-loop 2 '()))


You write a faster program if you use Sieve of Eratosthenes.
Sieve of Eratosthenes - Wikipedia, the free encyclopedia

Feb 4, 2008

"prototype" of JavaScript.

I decided to learn "prototype" of JavaScript.
Prototype-base object oriented programming seems to be interesting.

Feb 3, 2008

Lambda calculus.

I'm interested in Lambda calculus.
It's too difficult for me.
But I do the best to understand it.

Feb 2, 2008

Many programming languages for .NET.

Many .NET languages are introduced in this page.

.NET Languages

I have used Ruby for .NET.
I'm interesting in Scheme for .NET.

I want to make Scheme.NET.

Feb 1, 2008

Combination of Ruby and Silverlight.

A Ruby CGI program outputs JavaScript for Silverlight.

http://tech.upper.jp/droptext/word/(a word you like)

Example:
http://tech.upper.jp/droptext/word/Hello,%20world%21

Jan 31, 2008

Simple AI (Neural network) program by Ruby.

Neural network is an algorithm of AI (Artificial intelligence).

I wrote a symple Neural network program by Ruby.

This program judge if the total price of three candies are under the limit.


class Unit
def initialize(count=3)
@cells = []
(count + 1).times { @cells << rand(9) }
end

def learn(patterns)
while !ok ||= false
ok = true
result = []
patterns.values.each do |pattern|
ans = answer(pattern)
chk = patterns.check(pattern)
if ans == chk
result << 'OK'
elsif ans && !chk
result << 'NG'
ok = false
penalize(pattern, -1)
elsif !ans && chk
result << 'NG'
ok = false
penalize(pattern, 1)
end
end
yield(ok, result, @cells)
end
end

def answer(pattern)
sum = 0
@cells.length.times { |i| sum += @cells[i + 1] if pattern[i] == 1 }
@cells[0] <= sum
end

def penalize(pattern, direction)
@cells[0] -= direction
@cells.length.times { |i| @cells[i + 1] += direction if pattern[i] == 1 }
end
end

class Patterns
def initialize
@limit = 500
@prices = [310,220,70]
@values = [[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]]
end

attr_reader :values

def check(pattern)
sum = 0
pattern.length.times { |i| sum += @prices[i] * pattern[i] }
sum <= @limit
end
end

#--------------------------------
unit = Unit.new
pat = Patterns.new
unit.learn(pat) do |ok, result, cells|
p result
break if gets =~ /x/
end

Jan 30, 2008

Simple AI (Generic Algorithm) program by Ruby.

Generic Algorithm is an algorithm of AI (Artificial intelligence).

I wrote a symple Generic Algorithm program by Ruby.

It answers multiple-choice questions.


class Genes
def initialize(gene_count=10, quiz_count=10)
@generation = 1
@quiz = Quiz.new(quiz_count)
while max == quiz_count
@genes = []
gene_count.times { |i| @genes << Gene.new(quiz_count) }
mark()
sort()
end
end

def start
while max < @quiz.count
yield(@generation, @genes, max, min, average)
next_genration()
mark()
sort()
end
yield(@generation, @genes, max, min, average)
end

def mark
@genes.length.times { |i| @genes[i].score = @quiz.mark(@genes[i].ans) }
end

def sort
@genes.sort! { |a, b| a.score <=> b.score }.reverse!
end

def next_genration
@generation += 1
pair = []
pair << @genes[0]
pair << @genes[1]
pair = breed(pair)
@genes[@genes.length - 2] = pair[0]
@genes[@genes.length - 1] = pair[1]
end

def breed(parents)
c = parents[0].count
children = [Gene.new(c), Gene.new(c)]
cross = rand(c - 1)
c.times do |i|
n = (i < cross) ? 0 : 1
children[0].ans[i] = parents[(0+n)%2].ans[i]
children[1].ans[i] = parents[(1+n)%2].ans[i]
end

mutation = rand(c)
children[0].ans[mutation] = rand(3) if mutation < c
mutation = rand(c)
children[1].ans[mutation] = rand(3) if mutation < c
children
end

def max
@genes ? @genes[0].score : @quiz.count
end

def min
@genes ? @genes[(@genes.length - 1)].score : 0
end

def average
sum = 0
@genes.each { |x| sum += x.score }
sum / @genes.length
end
end

class Gene
def initialize(count)
@count = count
@ans = []
@count.times { |i| @ans << rand(3) }
end

attr_accessor :score
attr_reader :ans
attr_reader :count
end

class Quiz < Gene
def mark(ans)
score = 0
@count.times { |i| score += 1 if @ans[i] == ans[i] }
score
end
end

#--------------------------------
g = Genes.new
g.start do |generation, genes, max, min, average|
p generation
p max
10.times do |i|
p genes[i].ans
end
break if gets =~ /x/
end

Jan 29, 2008

Currying of a function with unfixed argument.

Some examples of Function Currying.


(define (curried+ a)
(lambda (b) (+ a b)))

((curried+ 1) 2)



(define (curried-mean a)
(lambda (b)
(lambda (c) (/ (+ (+ a b) c) 3))))

(((curried-mean 1) 2) 3)



When the function has arguments with which the number is unfixed.


(define (append lst x)
(if (null? lst)
(list x)
(let ((l (if (list? lst) lst (list lst))))
(cons (car l) (append (cdr l) x)))))

(define (curried-list x)
(lambda (y)
(if (null? y)
x
(curried-list (append x y)))))

(((((curried-list 1) 2) 3) 4) '())


"'()" is unwanted...

Jan 28, 2008

Tail recursion of Scheme.

Ruby program for Fibonacci number.


def fib(n)
if n < 2
n
else
fib(n - 2) + fib(n - 1)
end
end



Scheme program for Fibonacci number.


(define (fib n)
(if (< n 2)
n
(+ (fib (- n 1)) (fib (- n 2)))))



Tail recursion version.


(define (fib n)
(define (fib-iter n a b)
(if (zero? n)
a
(fib-iter (- n 1) b (+ a b))))
(fib-iter n 0 1))


Scheme has "tail recursion optimization".
Then Scheme is faster than Ruby with optimization.

Jan 27, 2008

The one line C#3.0 program for Fibonacci numbers.

I wrote one line Ruby program for Fibonacci numbers.
The one line Ruby program for Fibonacci numbers.

And I wrote one line C#2.0 program for it.
The one line C#2.0 program for Fibonacci numbers.


C#3.0 program is more elegant than C#2.0 program.

Let's write one line C#3.0 program for Fibonacci numbers.

This is the result.

1
1
2
3
5
8
13
21
34
55

This is the one line C#2.0 program.

new EventHandler(delegate(object s,EventArgs e){while(((int[])s)[2]++<10)if(Console.WriteLine(((int[])s)[1]=(((int[])s)[0]=((int[])s)[0]+((int[])s)[1])-((int[])s)[1])is Object){}}).Invoke(new int[]{1,0,0},null);


And this is the one line C#3.0 program.

Enumerable.Repeat(new[]{1,0},10).All(x=>!(Console.WriteLine(x[1]=((x[0]=x[0]+x[1])-x[1]))is Object));


More elegant!

Jan 26, 2008

The one line C#2.0 program for Fibonacci numbers.

I wrote one line Ruby program for Fibonacci numbers.
The one line Ruby program for Fibonacci numbers.

Ruby is a dynamically-typed programming language.
C# is a statically-typed programming language.

Let's write one line C#2.0 program for Fibonacci numbers.

This is the result.

1
1
2
3
5
8
13
21
34
55

This is the one line program.

new EventHandler(delegate(object s,EventArgs e){while(((int[])s)[2]++<10)if(Console.WriteLine(((int[])s)[1]=(((int[])s)[0]=((int[])s)[0]+((int[])s)[1])-((int[])s)[1])is Object){}}).Invoke(new int[]{1,0,0},null);


This is the statically-typed programming language.

Jan 25, 2008

"Jobs Hacks" are not for sale.



I made this "O'Reilly Maker".
O'Reilly Maker - Create a funny book cover!
O'Reilly Maker - Jobs hacks


From Steve Jobs Stanford Commencement Speech 2005.

"Keep looking. Don't settle."

"Your time is limited, so don't waste it living someone else's life."

"Stay Hungry. Stay Foolish."

Jan 24, 2008

The one line Ruby program for Fibonacci numbers.

Let's write one line Ruby program for Fibonacci numbers.

This is the result.

1
1
2
3
5
8
13
21
34
55

This is the one line program.

lambda{|a,b|10.times{p b=(a=a+b)-b}}.call(1,0)


Smart?

Jan 23, 2008

Can't use "document.body" on Safari.

It's impossible to use "document.body" on Safari when the web page is XHTML.
Then this code return "undefined".

alert(typeof(document.body));



But it comes no always.
What is the condition?


"document.documentElement" is OK.

Jan 22, 2008

Read Offline for iPhone/iPod touch

I made a bookmarklet for iPhone/iPod touch.
You can read web pages on iPhone/iPod touch when you are offline.

Read Offline for iPhone/iPod touch

I'm glad to read web pages offline.

Jan 21, 2008

JavaScript Shell for iPhone/iPod touch

JavaScript Shell for iPhone/iPod touch was released.

You can write and execute JavaScript programs on iPhone/iPod touch even if you are offline.


This is bookmarklet version.
JavaScript Shell for iPhone/iPod touch

It's posible to save your script with ver.2.
JavaScript Shell for iPhone/iPod touch (ver.2)


Sample code:

Show messagebox.

alert("Hello, world");



Calculate fibonacci.

function fib(n) {
if (n < 2) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
fib(10);


Operate DOM.

document.getElementById("area").style.color = "blue";
document.getElementById("result").style.color = "red";
document.getElementById("exec").innerHTML = "Execute!!!!";
document.getElementById("save").innerHTML = "Save!!!!";



Let's enjoy programming on iPhone/iPod touch.

Jan 20, 2008

iPod touch firmware update to 1.1.3

I updated my iPod touch firmware to 1.1.3.

The information about the firmware 1.1.3 and the software update is mixed.
The firmware 1.1.3 is free.
Software update is nonfree ($20).

The firmware is good for Japanese users.
Because of the improvement of Japanese keybord.

I'm looking forward to the SDK for iPhone/iPod touch released next month.

Jan 17, 2008

The one line Ruby program for the factorial of n (n!)

Write a program that calculates the facctorial of n (n!).

result = n * (n - 1) * (n - 2) * ... * 2 * 1


I write a Ruby program.
n = gets.to_i
k = 1
n.times do |i|
k *= i.next
end
puts k
This is a normal program.
Let's write in one line.

k = 1
gets.to_i.times { |i| k *= i.next }
puts k
It's easy so far.


A little device.
k = 1
puts k if gets.to_i.times { |i| k *= i.next }

The key point is the initialization of a variable.
lambda { |k| puts k if gets.to_i.times { |i| k *= i.next } }.call(1)
Completion!

Jan 16, 2008

My iPod touch can't access WiFi.

I want to jailbreak for my iPod touch.
But my iPod touch can't access WiFi.
The wireless connection is unstable.

Should I buy other wireless router?

Jan 15, 2008

Trying iPod touch

I got an iPod touch.
And got a case for it.

But the case is not good.
I will buy a new case.

Jan 14, 2008

From Japanese programmer.

I use C# at office and Ruby at home.
Now I'm interested in JavaScript.

I've just been reading "The Pragmatic Programmer" written by Andrew Hunt and David Thomas.