Peter Norvig’s Spelling Corrector in Go

February 15, 2012

Just for fun, I rewrote Peter Norvig’s well-known spelling corrector in the Go programming language. The up-to-date code is at here. A snapshot of it is:

package main

import (
	"io/ioutil"
	"regexp"
	"fmt"
	"strings"
)

func train(training_data string) map[string]int {
	NWORDS := make(map[string]int)
	pattern := regexp.MustCompile("[a-z]+")
	if content, err := ioutil.ReadFile(training_data); err == nil {
 		for _, w := range pattern.FindAllString(strings.ToLower(string(content)), -1) {
			NWORDS[w]++;
		}
	} else {
		panic("Failed loading training data.  Get it from http://norvig.com/big.txt.")
	}
	return NWORDS
}

func edits1(word string, ch chan string) {
	const alphabet = "abcdefghijklmnopqrstuvwxyz"
	type Pair struct{a, b string}
	var splits []Pair
	for i := 0; i < len(word) + 1; i++ {
		splits = append(splits, Pair{word[:i], word[i:]}) }

	for _, s := range splits { // deletes
		if len(s.b) > 0 { ch <- s.a + s.b[1:] }}
	for _, s := range splits { // transposes
		if len(s.b) > 1 { ch <- s.a + string(s.b[1]) + string(s.b[0]) + s.b[2:] }}
	for _, s := range splits { // replaces
		for _, c := range alphabet { if len(s.b) > 0 { ch <- s.a + string(c) + s.b[1:] }}}
	for _, s := range splits { // inserts
		for _, c := range alphabet { ch <- s.a + string(c) + s.b }}
}

func edits2(word string, ch chan string) {
	edits1ch := make(chan string, 10)
	go func() {
		edits1(word, edits1ch)
		ch <- ""}()
	for e1 := range edits1ch {
		if e1 == "" { break }
		edits1(e1, ch)
	}
}

func correct(word string, NWORDS map[string]int) string {
	ch := make(chan string)
	go func() {
		ch <- word
		edits1(word, ch)
		edits2(word, ch)
		ch <- ""
	}()
	maxFreq := 0
	correction := ""
	for word := range ch {
		if word == "" { return correction }
		if freq, present := NWORDS[word]; present && freq > maxFreq {
			maxFreq, correction = freq, word
		}
	}
	return ""
}

func main() {
	model := train("big.txt")
	fmt.Println(correct("speling", model))
	fmt.Println(correct("korrecter", model))
}

I used 57 non-empty lines of source code to express this algorithm in Go. For numbers of lines with other programming languages, please scroll down to the end of the original post.


6502 —— 伟大的心(上)

February 8, 2012

【转载请注明作者:王益,以及原创 URL:http://cxwangyi.wordpress.com/2012/02/08/6502-伟大的心(上)/。】

今天,当我们说起个人电脑,大家没法不联想到 Intel(以及 AMD)处理器。然而,个人电脑的幼年时期,很多个人电脑用的是一种叫 MOS 6502 的处理器。

今天在 Russ Cox(Google Go语言的设计者之一)的博客上,看到一篇介绍 6502 处理器的帖子:http://research.swtch.com/6502 。6502 对我来说是一个很亲切的名字:我小学三年级(应该是1985年)的时候,爸爸买了一台中华学习机I型。其实是中科院仿制的 Apple II。而 Apple II 是 Steve Jobs 的成名作。在 Paul Graham 的《Hackers and Painters》一书中,被评价为开启了个人拥有电脑的时代。在我初中的时候,开始在中华学习机上写汇编语言程序。当时把 6502 的指令集几乎都背下来了。

前两年看到一本很有意思的书,叫《我们台湾这些年》;作者和我同年。他提到台湾宏基电脑公司在八十年代曾经出品了一款叫“小博士”的个人电脑,也是 Apple II 的仿制品。从这些仿制故事里,大家估计不难理解为什么 Steve Jobs 不愿把后来的 Machintosh 电脑和 iPhone、iPad 做成 IBM PC 和 Android 那样的开放体系了。

看了 Russ Cox 的这篇帖子,我才注意到其实远不止是 Apple II 和它的各种克隆用了 6502。上个世纪七八十年代最赫赫有名的计算机系统中大多使用了 6502 处理器。为此,把 Russ Cox 的这篇帖子翻译成中文:

原文标题:MOS 6502 处理器和最棒的芯片布局设计师

在上世纪七八十年代,6502 处理器无处不在:6502 是 Apple II、Atari 2600、BBC Micro、Commondore 64 以及任天堂的游戏机的核心。想想都觉得了不起!因为这五种计算机中的每一种在当年都是威名赫赫。

6502 是 Chuck Peddle 的智慧结晶。Chuck Peddle 当时是摩托罗拉公司 Motorola 6800 处理器项目的工程师。他的一项工作就是向客户兜售 6800 处理器。(Peddle 在英语里恰好是“兜售”的意思。)6800 深受客户青睐,但是就是太贵了——标价300美元。为此,Peddle 试图说服摩托罗拉的管理层设计一种廉价处理器,可是 6800 处理器带来的利润已经不错了,管理层因此含糊的表示了没必要搞一种新的处理器。作为回复,Peddle 和其他一些 6800 处理器的工程师们离开的摩托罗拉公司建立了 MOS Technology 公司,并且开发了 6502 处理器 —— 单价25美元。虽然 6502 和 6800 的主频一样,都是 1MHz,但是因为 6502 有一个指令流水线(在一条指令执行的同时,就取下一条指令),从而性能显著优于 6800。十分之一的价格和更棒的性能导致 6502 四处热卖。

6502 的故事构成了 Brian Bagnall 的新书《On the Edge: the Spectacular Rise and Fall of Commodore》中的第一章。我(Russ Cox)最喜欢这本书里关于 6502 处理器的设计过程的部分。现在的处理器很复杂了,比如 Intel Core 2 处理器有上亿个晶体管 —— 要是没有电脑的帮助,咱没法手工设计处理器的布局。(译者:布局、layout、指的是决定集成电路中的晶体管的位置。与之相关的一个过程称为 rolling,指晶体管之间连线。)6502 处理器只有3510个晶体管 —— 一个叫 Bill Mensch 的工程师手工设计了 6502 的电路图。

布局结束后,需要把电路图画在一张胶片上,随后用类似洗照片的光刻技术,按照胶片上的内容在硅片上刻出电路。6502的胶片和一张大桌子一样大,工程师们可以趴在上面绘制。当时大家都得穿着很干净的袜子。袜子不能有洞。要不然脚趾甲可能划坏胶片。

最牛鼻的是:这帮人一次成功地搞定了整个设计和制造过程!

【待续】


Jailbreaking iPhone: Installing Perl and Python

February 4, 2012

It is easy to install Python and jail breaking and installing Cydia:

sudo apt-get install python

It is a little more complex to install Perl. You should follow instructions here to add a new repository and its GPG key.


Jailbreaking iPhone: Using apt-get on iPhone

February 4, 2012

After jail-breaking your iPhone, you can install CyDelete from Cydia. This also brings you apt-get and apt-cache.


Jailbreaking iPhone: 挽救 iPhone 4 砖头机

January 31, 2012

很不好意思的,在把 iPhone 4 变成一台开发机之后,我的一个误操作把它变成了砖头机:

为了把 XCode 里 iPhone SDK 中的 header files 和 library files 拷贝到我的 iPhone 上(这么干好像是违反 iPhone 和 XCode users licence 的),我想敲两个命令:

sudo mv /usr/lib /usr/lib.bak
sudo ln -s ~/Media/iPhoneSDK/lib /usr/lib

结果很不幸的,第一个命令一敲完,系统就死了。(我没有在 Linux 或者 FreeBSD 上这么干过,不知道这俩会不会死。)

随后用 macbook 上的 iTunes 回复 iPhone 的系统。不知什么原因,我开会回来时,发现雪上加霜—— iPhone 砖头了。而且屏幕上是花的,无法关机。

于是开始了慢慢长征路:先找卖给我这个 iPhone 的中关村小铺,说无解。于是去西单大悦城的苹果店的 Genius Bar,说我买的是港版,没有发票也无法开机,不给保修。于是去了一家苹果指定维修店,一看77个人排队在我前头,而且唯一的工程师甩着淳朴的京片儿,一副憨憨的无知少年的样子。

最关键的是:在这些地方都没有看到我心中设想的高级维修设备,工程师们也都是用笔记本电脑连上 iPhone 修理。于是哥们儿心说,既然有按照百度开方子的医生,何不在自己动手 google 一下呢?难道维修工程师们的英语水平比哥这个开发工程师还牛了去了?!

于是发现可以进入 DFU mode(怎么进入请 Google)然后 iPhone 就又能被 iTunes 发现并且 restore 了。DFU mode 是执行 firmware 中的程序,但是不引导操作系统。

但是 restore 很不好意思的又失败了;给出一个错误消息说:error 3004。继续 Google,发现这里有(http://support.apple.com/kb/TS3694)各种error code 的应对方法。在执行了一个神妙命令之后,再次 restore 成功。

随后还从 iTunes 的备份中恢复了通信录、短信记录、以及配置好的邮箱和邮件等重要信息。

准备明天再次翻墙。这次要不仅要装 gcc 4.2 和 Google Go for iOS,还立志要把 Clang/LLVM 移植到 iPhone 4 上来!


Jailbreaking iPhone: 把 iPhone 变成一台开发工作站

January 29, 2012

iPhone 和 iPad 内部基本上是 CMU 的 Mach 内核上运行着的 NetBSD 操作系统服务。从这些出色的操作系统技术来看, iPhone 和 iPad 不逊色于任何一款电脑。

自从买了 iPhone 4,我一直在琢磨着怎么怎么把它变得跟一台开发用的电脑一样,比如像装了开发环境(Homebrew)的 Mac MINI 一样。从 Apple Store 上买了一根 iPhone/iPad to VGA 适配电缆之后,我的 iPhone 可以输出到电视和显示器。在 jailbreak 工具(redsn0w)和 Cydia 的帮助下,我可以把 iPhone 和无线键盘、无限鼠标连接起来。我还安装了 iPhone 上的 Mobile Terminal  和一些常用的工具程序,包括和 awk 和 vim。随后,感谢牛鼻的黑客们提供了 GCC 4.2 和 Google Go compiler 的 iPhone 版本。然后呢,用 iPhone 写程序大概就是这个样子的(我其实可以把 iPhone 横过来,这样更能充分利用电视宽屏的空间;图中配角男还应该减减肥):

在 iPhone 上用 vim 编辑 C 语言和 Go 语言程序的样子如下:

 

编译和运行程序的样子是这样的:

 

附上一些秘笈:

  • Cydia 里默认的 Mobile Terminal 版本低,在 iOS 5 上会crash。安装 up-to-date 的 Mobile Terminal:http://iphonejailbreaks.org/mobile-terminal-crashes-on-ios-4-3-1-here-is-the-solution/
  • 在手机上用 Mobile Terminal,如果没有无限键盘,敲键太慢。通常是通过电脑 ssh 到 iPhone 的:http://www.cultofmac.com/32134/access-your-iphone-file-system-with-ssh-jailbreak-superguide/
  • 在 Apple Store 上购买 iPhone/iPad 的 VGA 转接电缆:http://store.apple.com/us/product/MC552ZM/B
  • 在 Cydia 上安装一个叫 DisplayOut 的软件,把 iPhone 屏幕上的内容通过电缆输出到电视或者显示器上。如果没有安装这个软件,只有部分 iPhone 程序能输出到 VGA。
  • 在 Cydia 上安装一个叫 BT Keyboard 的程序让 iPhone 可以连接无线键盘
  • 在 Cydia 上安装一个叫 BT Mouse 的程序让 iPhone 可以连接无线鼠标
  • 在 iPhone 上安装 GCC 4.2:http://cxwangyi.wordpress.com/2012/01/28/how-to-install-gcc-4-2-on-iphone/
  • 在 iPhone 上用 GCC build Google Go 语言的编译器:http://cxwangyi.wordpress.com/2012/01/28/learning-go-go-for-iphoneipad/

Learning Go: Go for iPhone/iPad

January 28, 2012

Strictly speaking, it is hard to say that this post is about “learning” the Go language. I just want to tell a story: after I successfully (but might illegally) installed GCC 4.2 on my iPhone 4, I went on to build Go. However, I got the following error messages:

Make.inc:79: *** Invalid $GOOS ‘darwin’ for GOARCH=arm; must be linux. Stop.
Did not find Go environment variables.

Then I searched “go darwin arm” in go-nuts group, the result leads me to a very new (Jan 7, 2012) and exciting work — a darwin/arm port of Go.

However, I also noticed a claim by the Go authors at the bottom of the discussion thread:

Date: Sat, 21 Jan 2012 15:48:18 -0500
Subject: Re: [golang-dev] Re: Darwin/ARM (aka. iOS) port of Go is READY
From: Russ Cox
To: minux
Cc: golang-dev@googlegroups.com

Sorry, I meant to reply about this before. We have decided
not to include the darwin/arm code in the main tree until there
is a way to run it on an ordinary iDevice without any kind of
“jailbreaking”. If the port advances to that point, please let
us know, but until then I’m afraid you’ll need to maintain your
own copy.

What a pitty for the official Go community~~ But so what! My best appreciation to minux, the author of the Darwin/ARM port of Go.


Jailbreaking iPhone: How to Install GCC 4.2 on iPhone

January 28, 2012

Following this blog post: http://blog.syshalt.net/index.php/2010/09/12/compile-c-applications-with-gcc-on-ios-4-iphone/, I installed GCC 4.2.1 on my iPhone and gcc works.  However, g++ does not.  Moreover, above post does not explain how comes the header files and library files for gcc on iPhone.

This post complements above post by adding the part about C++.  First of all, I copy-and-pastes above post.

———————————————-

Here is what you need to do in order to be able to compile and run a C application on iphone:

1. You will need to Jailbreak the iPhone first, search on google for more info.
2. Install OpenSSH from Cydia.
3. Connect iPhone to your wireless network and SSH to it.
4. Download this application using: wget http://www.syshalt.net/pub/iphone/gcc-iphone/fake-libgcc_1.0_iphoneos-arm.deb
5. Install libcc using: dpkg –i fake-libgcc_1.0_iphoneos-arm.deb
6. Install iphone-gcc using this command: apt-get install iphone-gcc
(you can download this version from my website: iphone-gcc if does not work on your device the one that is installed by default)
7. Download using: wget http://www.syshalt.net/iphone/gcc-iphone/sdk-2.0-headers.tar.gz
8. Untar with command: tar -xvzf sdk-2.0-headers.tar.gz
9. Enter in the new created folder with: cd include-2.0-sdk-ready-for-iphone
10. Copy all files to include folder with command: cp –r * /usr/include
11. Now type: cd .. in order to return to the previous folder
12. Download using: wget http://www.syshalt.net/iphone/gcc-iphone/gcc_files.tar.gz
13. Untar with command: tar -xvzf gcc_files.tar.gz
14. Enter in the new created folder with command: cd gcc_files
15. Copy all files to /usr/lib using command: cp –r * /usr/lib
16. Install ldid to sign the application (this will prevent iOS to kill the application at startup) using: apt-get install ldid
17. Sign your compilet aplication using: ldid –S <application>
18. Run the application using: ./<application>

——————————————–

From step 9 to step 15, it explains how to install C header files and library files. These files can be copied from the iPhone SDK. On my MacBook, I have Xcode 4.1 and iPhone SDK 4.3, which resides in the directory:

/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk

I just package the usr subdirectory and throw it to my iPhone:

tar cjf iPhoneOS4.3.sdk-usr.tar.bz2 \
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/usr
scp iPhoneOS4.3.sdk-usr.tar.bz2 mobile@:/var/mobile/Media/

Then, on my iPhone, I unpack the tarball and installed the packing using the following commands:

cd /var/mobile/Media
tar xjf iPhone4.3.sdk-usr.tar.bz2
cd /usr/local
sudo ln -s /var/mobile/Media/iPhoneOS4.3.sdk-usr/include
cd /usr/lib
sudo ln -s /var/mobile/Media/iPhoneOS4.3.sdk-usr/lib/libSystem.B.dylib
sudo ln -s /var/mobile/Media/iPhoneOS4.3.sdk-usr/lib/libSystem.dylib
sudo ln -s /var/mobile/Media/iPhoneOS4.3.sdk-usr/lib/libgcc_s.1.dylib
sudo rmdir system
sudo ln -s /var/mobile/Media/iPhoneOS4.3.sdk-usr/lib/system
for i in  /var/mobile/Media/iPhoneOS4.3.sdk-usr/lib/libstdc++*; do \
sudo ln -s $i; done

It is now the time to test g++. Using the following command:

g++ hello.cc -o hello \
-I /usr/local/include/c++/4.2.1/ \
-I /usr/local/include/c++/4.2.1/armv7-apple-darwin10

I successfully built the following simple C++ program:

#include <stdio.h>

int main() {
        std::cout << "Hello World!";
        return 0;
}

Using Clang: C++0x Features

January 23, 2012

I am using Ubuntu Linux 10.10, with which, comes Clang based on LLVM 2.8. When I use Clang to build google-test, it complains that “variadic template” is a C++0x feature and is not yet supported.

However, the Clang installed by Homebrew on my Mac OS X 10.7 (Lion) is based on LLVM 3.0 and works well with google-test.

The homepage of LLVM listed pre-built Clang and LLVM 3.0 for Ubuntu 11.04 and 11.10. So I guess I would have to upgrade to at least Ubuntu 11.04.

FreeBSD 9.0 comes with Clang based on LLVM 3.0.


Python under Linux, Mac OS X and FreeBSD Tells Differently

January 21, 2012

It is interesting: under Linux and Mac OS X running on x64 computers, Python 2.7 tells the machine is ‘x64_64′; whereas under FreeBSD, Python 2.7 tells ‘amd64′. You can try:
import platform
platform.machine()


Follow

Get every new post delivered to your Inbox.