<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.3.1" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>Nirvana Studio</title>
	<link>http://www.nirvanastudio.org</link>
	<description>分享知识，传播技术</description>
	<pubDate>Tue, 01 Jan 2008 14:51:11 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.1</generator>
	<language>en</language>
			<item>
		<title>新年快乐及改版通知</title>
		<link>http://www.nirvanastudio.org/news/happy-new-year.html</link>
		<comments>http://www.nirvanastudio.org/news/happy-new-year.html#comments</comments>
		<pubDate>Tue, 01 Jan 2008 14:51:11 +0000</pubDate>
		<dc:creator>ShiningRay</dc:creator>
		
		<category><![CDATA[新闻]]></category>

		<guid isPermaLink="false">http://www.nirvanastudio.org/news/happy-new-year.html</guid>
		<description><![CDATA[在过去的一年里，由于Nirvana Studio的各个成员各奔东西投入紧张的工作，没有能贡献更多的技术文正，我们在这里深表歉意。
经过2007年一年的调整，工作生活让我们在技术上有了更多的经验和感悟，我们希望在新的一年里能给大家带来更多新的知识，分享更多好的心得。为了能更好地给朋友们提供信息，我们将在1月份对网站进行整体改版，期间可能访问会出现异常，请大家谅解。我们期望通过改版使新网站有更高的品质，给大家带来新的气息，新的氛围。
最后在这里，NirvanaStudio的Athisika, iCream, IoriKrace, Nicholas, ShiningRay在这里祝大家新年快乐，学习进步！
]]></description>
			<content:encoded><![CDATA[<p>在过去的一年里，由于Nirvana Studio的各个成员各奔东西投入紧张的工作，没有能贡献更多的技术文正，我们在这里深表歉意。</p>
<p>经过2007年一年的调整，工作生活让我们在技术上有了更多的经验和感悟，我们希望在新的一年里能给大家带来更多新的知识，分享更多好的心得。为了能更好地给朋友们提供信息，我们将在1月份对网站进行整体改版，期间可能访问会出现异常，请大家谅解。我们期望通过改版使新网站有更高的品质，给大家带来新的气息，新的氛围。</p>
<p>最后在这里，NirvanaStudio的<a href="http://athisika.nirvanastudio.org">Athisika</a>, <a href="http://www.icream.cn">iCream</a>, <a href="http://iorikrace.nirvanastudio.org">IoriKrace</a>, <a href="http://www.nicholasding.com">Nicholas</a>, <a href="http://shiningray.cn">ShiningRay</a>在这里祝大家新年快乐，学习进步！</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nirvanastudio.org/news/happy-new-year.html/feed</wfw:commentRss>
		</item>
		<item>
		<title>Ubuntu 完美中文字体</title>
		<link>http://www.nirvanastudio.org/news/ubuntu-yuanti.html</link>
		<comments>http://www.nirvanastudio.org/news/ubuntu-yuanti.html#comments</comments>
		<pubDate>Thu, 26 Apr 2007 09:19:13 +0000</pubDate>
		<dc:creator>Nicholas Ding</dc:creator>
		
		<category><![CDATA[Ubuntu]]></category>

		<category><![CDATA[新闻]]></category>

		<guid isPermaLink="false">http://www.nirvanastudio.org/news/ubuntu-yuanti.html</guid>
		<description><![CDATA[Ubuntu 每次升级几乎都会调整 fonts.conf 的内容，所以 wiki.ubuntu.org.cn 上提供的 VeraSansYuanTi 的字体配置就不能够直接替换系统默认的 fonts.conf 文件。
圆体的下载地址和参考配置在 Ubuntu Wiki 上的 使用圆体美化系统
这里提供了一份 Nicholas 手工合并过的版本，适合 Ubuntu 7.04 Feisty Fawn，完美显示圆体效果。需要替换 /etc/fonts.conf 和另外两个文件 /etc/fonts/conf.avail/40-generic.conf 和 /etc/fonts/conf.avail/60-latin.conf
下载 fonts.conf 40-generic.conf 60-latin.conf
效果图

]]></description>
			<content:encoded><![CDATA[<p>Ubuntu 每次升级几乎都会调整 fonts.conf 的内容，所以 wiki.ubuntu.org.cn 上提供的 VeraSansYuanTi 的字体配置就不能够直接替换系统默认的 fonts.conf 文件。</p>
<p>圆体的下载地址和参考配置在 Ubuntu Wiki 上的 <a href="http://wiki.ubuntu.org.cn/%E4%BD%BF%E7%94%A8%E5%9C%86%E4%BD%93%E7%BE%8E%E5%8C%96%E6%B1%89%E5%AD%97">使用圆体美化系统</a></p>
<p>这里提供了一份 Nicholas 手工合并过的版本，适合 Ubuntu 7.04 Feisty Fawn，完美显示圆体效果。需要替换 /etc/fonts.conf 和另外两个文件 /etc/fonts/conf.avail/40-generic.conf 和 /etc/fonts/conf.avail/60-latin.conf</p>
<p>下载 <a href="http://www.nirvanastudio.org/nicholas/fonts.conf">fonts.conf</a> <a href="http://www.nirvanastudio.org/nicholas/40-generic.conf">40-generic.conf</a> <a href="http://www.nirvanastudio.org/nicholas/60-latin.conf">60-latin.conf</a></p>
<p>效果图</p>
<p><img id="image123" src="http://www.nirvanastudio.org/wp-content/uploads/2007/04/Screenshot.png" alt="效果图" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.nirvanastudio.org/news/ubuntu-yuanti.html/feed</wfw:commentRss>
		</item>
		<item>
		<title>如何给 Solaris 添加新 IDE 硬盘</title>
		<link>http://www.nirvanastudio.org/solaris/solaris-add-ide.html</link>
		<comments>http://www.nirvanastudio.org/solaris/solaris-add-ide.html#comments</comments>
		<pubDate>Fri, 06 Apr 2007 14:09:22 +0000</pubDate>
		<dc:creator>Nicholas Ding</dc:creator>
		
		<category><![CDATA[Solaris]]></category>

		<guid isPermaLink="false">http://www.nirvanastudio.org/solaris/%e5%a6%82%e4%bd%95%e7%bb%99-solaris-%e6%b7%bb%e5%8a%a0%e6%96%b0-ide-%e7%a1%ac%e7%9b%98.html</guid>
		<description><![CDATA[以 root 身份登录，键入以下命令：

touch /reconfigure
shutdown -y -i6

]]></description>
			<content:encoded><![CDATA[<p>以 root 身份登录，键入以下命令：<br/></p>
<p><code><br />
touch /reconfigure<br/><br />
shutdown -y -i6<br/><br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.nirvanastudio.org/solaris/solaris-add-ide.html/feed</wfw:commentRss>
		</item>
		<item>
		<title>OCaml模块</title>
		<link>http://www.nirvanastudio.org/ocaml/ocaml-modules.html</link>
		<comments>http://www.nirvanastudio.org/ocaml/ocaml-modules.html#comments</comments>
		<pubDate>Sat, 30 Sep 2006 08:18:59 +0000</pubDate>
		<dc:creator>ShiningRay</dc:creator>
		
		<category><![CDATA[OCaml]]></category>

		<guid isPermaLink="false">http://www.nirvanastudio.org/news/ocaml-modules.html</guid>
		<description><![CDATA[原文地址：http://www.ocaml-tutorial.org/modules，翻译：ShiningRay
模块（Module）是什么？我们首先看一下在OCaml内建的一些模块，比如可以先看一下List模块。首先让解释器将List模块的签名打印出来。这里有一个小技巧，我们可以将其复制一份自己的：
module MyList = List;;
然后就会打印出：
module MyList :
   sig
   val length : 'a list -&#62; int
   val hd : 'a list -&#62; 'a
   val tl : 'a list -&#62; 'a list
   val nth : 'a list -&#62; int -&#62; 'a
   val rev : 'a list [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>原文地址：<a href="http://www.ocaml-tutorial.org/modules" rel="external">http://www.ocaml-tutorial.org/modules</a>，翻译：<a href="http://wiki.nirvanastudio.org/wiki/ShiningRay">ShiningRay</a></p></blockquote>
<p>模块（Module）是什么？我们首先看一下在OCaml内建的一些模块，比如可以先看一下List模块。首先让解释器将List模块的签名打印出来。这里有一个小技巧，我们可以将其复制一份自己的：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">module</span> MyList = <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html"><span style="">List</span></a>;;</pre></p>
<p class="first_para">然后就会打印出：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">module</span> MyList :
   <span style="color: #06c; font-weight: bold;">sig</span>
   <span style="color: #06c; font-weight: bold;">val</span> length : 'a list -&gt; int
   <span style="color: #06c; font-weight: bold;">val</span> hd : 'a list -&gt; 'a
   <span style="color: #06c; font-weight: bold;">val</span> tl : 'a list -&gt; 'a list
   <span style="color: #06c; font-weight: bold;">val</span> nth : 'a list -&gt; int -&gt; 'a
   <span style="color: #06c; font-weight: bold;">val</span> rev : 'a list -&gt; 'a list
   <span style="color: #06c; font-weight: bold;">val</span> append : 'a list -&gt; 'a list -&gt; 'a list
   <span style="color: #06c; font-weight: bold;">val</span> rev_append : 'a list -&gt; 'a list -&gt; 'a list
   <span style="color: #06c; font-weight: bold;">val</span> concat : 'a list list -&gt; 'a list
   <span style="color: #06c; font-weight: bold;">val</span> flatten : 'a list list -&gt; 'a list
   <span style="color: #06c; font-weight: bold;">val</span> iter : <span style="color: #6c6;">&#40;</span>'a -&gt; unit<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; unit
   <span style="color: #06c; font-weight: bold;">val</span> map : <span style="color: #6c6;">&#40;</span>'a -&gt; 'b<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'b list
   <span style="color: #06c; font-weight: bold;">val</span> rev_map : <span style="color: #6c6;">&#40;</span>'a -&gt; 'b<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'b list
   <span style="color: #06c; font-weight: bold;">val</span> fold_left : <span style="color: #6c6;">&#40;</span>'a -&gt; 'b -&gt; 'a<span style="color: #6c6;">&#41;</span> -&gt; 'a -&gt; 'b list -&gt; 'a
   <span style="color: #06c; font-weight: bold;">val</span> fold_right : <span style="color: #6c6;">&#40;</span>'a -&gt; 'b -&gt; 'b<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'b -&gt; 'b
   <span style="color: #06c; font-weight: bold;">val</span> iter2 : <span style="color: #6c6;">&#40;</span>'a -&gt; 'b -&gt; unit<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'b list -&gt; unit
   <span style="color: #06c; font-weight: bold;">val</span> map2 : <span style="color: #6c6;">&#40;</span>'a -&gt; 'b -&gt; 'c<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'b list -&gt; 'c list
   <span style="color: #06c; font-weight: bold;">val</span> rev_map2 : <span style="color: #6c6;">&#40;</span>'a -&gt; 'b -&gt; 'c<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'b list -&gt; 'c list
   <span style="color: #06c; font-weight: bold;">val</span> fold_left2 : <span style="color: #6c6;">&#40;</span>'a -&gt; 'b -&gt; 'c -&gt; 'a<span style="color: #6c6;">&#41;</span> -&gt; 'a -&gt; 'b list -&gt; 'c list -&gt; 'a
   <span style="color: #06c; font-weight: bold;">val</span> fold_right2 :
     <span style="color: #6c6;">&#40;</span>'a -&gt; 'b -&gt; 'c -&gt; 'c<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'b list -&gt; 'c -&gt; 'c
   <span style="color: #06c; font-weight: bold;">val</span> for_all : <span style="color: #6c6;">&#40;</span>'a -&gt; bool<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; bool
   <span style="color: #06c; font-weight: bold;">val</span> exists : <span style="color: #6c6;">&#40;</span>'a -&gt; bool<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; bool
   <span style="color: #06c; font-weight: bold;">val</span> for_all2 : <span style="color: #6c6;">&#40;</span>'a -&gt; 'b -&gt; bool<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'b list -&gt; bool
   <span style="color: #06c; font-weight: bold;">val</span> exists2 : <span style="color: #6c6;">&#40;</span>'a -&gt; 'b -&gt; bool<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'b list -&gt; bool
   <span style="color: #06c; font-weight: bold;">val</span> mem : 'a -&gt; 'a list -&gt; bool
   <span style="color: #06c; font-weight: bold;">val</span> memq : 'a -&gt; 'a list -&gt; bool
   <span style="color: #06c; font-weight: bold;">val</span> find : <span style="color: #6c6;">&#40;</span>'a -&gt; bool<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'a
   <span style="color: #06c; font-weight: bold;">val</span> filter : <span style="color: #6c6;">&#40;</span>'a -&gt; bool<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'a list
   <span style="color: #06c; font-weight: bold;">val</span> find_all : <span style="color: #6c6;">&#40;</span>'a -&gt; bool<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'a list
   <span style="color: #06c; font-weight: bold;">val</span> partition : <span style="color: #6c6;">&#40;</span>'a -&gt; bool<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'a list * 'a list
   <span style="color: #06c; font-weight: bold;">val</span> assoc : 'a -&gt; <span style="color: #6c6;">&#40;</span>'a * 'b<span style="color: #6c6;">&#41;</span> list -&gt; 'b
   <span style="color: #06c; font-weight: bold;">val</span> assq : 'a -&gt; <span style="color: #6c6;">&#40;</span>'a * 'b<span style="color: #6c6;">&#41;</span> list -&gt; 'b
   <span style="color: #06c; font-weight: bold;">val</span> mem_assoc : 'a -&gt; <span style="color: #6c6;">&#40;</span>'a * 'b<span style="color: #6c6;">&#41;</span> list -&gt; bool
   <span style="color: #06c; font-weight: bold;">val</span> mem_assq : 'a -&gt; <span style="color: #6c6;">&#40;</span>'a * 'b<span style="color: #6c6;">&#41;</span> list -&gt; bool
   <span style="color: #06c; font-weight: bold;">val</span> remove_assoc : 'a -&gt; <span style="color: #6c6;">&#40;</span>'a * 'b<span style="color: #6c6;">&#41;</span> list -&gt; <span style="color: #6c6;">&#40;</span>'a * 'b<span style="color: #6c6;">&#41;</span> list
   <span style="color: #06c; font-weight: bold;">val</span> remove_assq : 'a -&gt; <span style="color: #6c6;">&#40;</span>'a * 'b<span style="color: #6c6;">&#41;</span> list -&gt; <span style="color: #6c6;">&#40;</span>'a * 'b<span style="color: #6c6;">&#41;</span> list
   <span style="color: #06c; font-weight: bold;">val</span> split : <span style="color: #6c6;">&#40;</span>'a * 'b<span style="color: #6c6;">&#41;</span> list -&gt; 'a list * 'b list
   <span style="color: #06c; font-weight: bold;">val</span> combine : 'a list -&gt; 'b list -&gt; <span style="color: #6c6;">&#40;</span>'a * 'b<span style="color: #6c6;">&#41;</span> list
   <span style="color: #06c; font-weight: bold;">val</span> sort : <span style="color: #6c6;">&#40;</span>'a -&gt; 'a -&gt; int<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'a list
   <span style="color: #06c; font-weight: bold;">val</span> stable_sort : <span style="color: #6c6;">&#40;</span>'a -&gt; 'a -&gt; int<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'a list
   <span style="color: #06c; font-weight: bold;">val</span> fast_sort : <span style="color: #6c6;">&#40;</span>'a -&gt; 'a -&gt; int<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'a list
   <span style="color: #06c; font-weight: bold;">val</span> merge : <span style="color: #6c6;">&#40;</span>'a -&gt; 'a -&gt; int<span style="color: #6c6;">&#41;</span> -&gt; 'a list -&gt; 'a list -&gt; 'a list
 <span style="color: #06c; font-weight: bold;">end</span></pre></p>
<p class="first_para">这个小技巧告诉了我们List模块所有可以用的东西。</p>
<p>让我们假设虽然我们要利用List模块，但是出于某种原因，我们要排除某些功能并加入一些其它功能。我们可以制作一个自己的List模块的版本。下面的例子去掉了“val length&#8230;”函数。首先要注意“include List”。这个语句将会把List模块的定义给我们拉进来。重新将length函数定义为抛出一个异常，只要加两行代码就行了。</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">module</span> MyList =
	<span style="color: #06c; font-weight: bold;">struct</span>
           <span style="color: #06c; font-weight: bold;">include</span> <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html"><span style="">List</span></a> 
           <span style="color: #06c; font-weight: bold;">exception</span> NO_LENGTH_ALLOWED
           <span style="color: #06c; font-weight: bold;">let</span> length l = <span style="color: #06c; font-weight: bold;">raise</span> NO_LENGTH_ALLOWED
       <span style="color: #06c; font-weight: bold;">end</span>;;</pre></p>
<p class="first_para">在下面一个例子中，我们就加入一个返回列表中任意一个元素的函数。我们还需要用到length函数，同时可能对于列表中没有任何元素的情况，还要加入另一个异常。</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">module</span> MyList =
       <span style="color: #06c; font-weight: bold;">struct</span>
           <span style="color: #06c; font-weight: bold;">include</span> <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html"><span style="">List</span></a> 
           <span style="color: #06c; font-weight: bold;">exception</span> EMPTY_LIST
           <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">rec</span> rand_element l = 
               <span style="color: #06c; font-weight: bold;">if</span> l = <span style="color: #6c6;">&#91;</span><span style="color: #6c6;">&#93;</span> <span style="color: #06c; font-weight: bold;">then</span> <span style="color: #06c; font-weight: bold;">raise</span> EMPTY_LIST
               <span style="color: #06c; font-weight: bold;">else</span> 
                   <span style="color: #06c; font-weight: bold;">let</span> len = <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALfloat_of_int"><span style="">float_of_int</span></a><span style="color: #6c6;">&#40;</span><a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html"><span style="">List</span></a>.<span style="color: #060;">length</span> l<span style="color: #6c6;">&#41;</span> <span style="color: #06c; font-weight: bold;">in</span>
                   <span style="color: #06c; font-weight: bold;">let</span> r = <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Random.html"><span style="">Random</span></a>.<a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALfloat"><span style="">float</span></a> <span style="color: #c6c;">1.0</span> <span style="color: #06c; font-weight: bold;">in</span>
                   <span style="color: #06c; font-weight: bold;">let</span> e = <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALint_of_float"><span style="">int_of_float</span></a><span style="color: #6c6;">&#40;</span>len *. <span style="color: #060;">r</span><span style="color: #6c6;">&#41;</span> <span style="color: #06c; font-weight: bold;">in</span>
                   <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html"><span style="">List</span></a>.<span style="color: #060;">nth</span> l e;;
       <span style="color: #06c; font-weight: bold;">end</span>;;</pre></p>
]]></content:encoded>
			<wfw:commentRss>http://www.nirvanastudio.org/ocaml/ocaml-modules.html/feed</wfw:commentRss>
		</item>
		<item>
		<title>OCaml函数式编程</title>
		<link>http://www.nirvanastudio.org/ocaml/functional-programming.html</link>
		<comments>http://www.nirvanastudio.org/ocaml/functional-programming.html#comments</comments>
		<pubDate>Sat, 23 Sep 2006 11:42:34 +0000</pubDate>
		<dc:creator>ShiningRay</dc:creator>
		
		<category><![CDATA[OCaml]]></category>

		<guid isPermaLink="false">http://www.nirvanastudio.org/ocaml/functional-programming.html</guid>
		<description><![CDATA[什么是函数式编程
我们已经在本教程中学了有一段时间了，然而我们还没有真正考虑过函数式编程（functional programming）。目前文中讲述的一系列特点——丰富的数据类型、模式匹配、类型推断、嵌套函数——这些你只能想像存在于某种“超级C”语言中。有了这些神奇特点之后，就能让你的代码更精炼、更容易阅读并且错误更少，但但实际上它们和函数式编程的关系却不是很大。事实上我要说的观点是函数式语言如此神奇并非是因为其函数式编程，而是因为我们长时间局限于类C语言之中，而同时编程的界限却在不断地继续扩展。所以当我们在第N次重复写struct { int type; union { ... } }的时候，ML和Haskell程序员已经可以对数据类型使用安全变体和模式匹配了。当我们还在小心翼翼地free每个我们所malloc的东西时，自从80年代就已经有能比手工编码更好的垃圾收集器了。
好吧，说完这些之后，我就可以告诉你什么是函数式编程了。
最基本的定义为（不过不是很让人明白的）：在函数式语言中，函数是第一等公民。
光说不练，难以令人理解，所以先看一个例子：
# let double x =
    x * 2
  in
  List.map double &#91; 1; 2; 3 &#93;;;
- : int list = &#91;2; 4; 6&#93;
在这个例子中，我首先定义了一个叫做double嵌套函数，输入一个参数x并返回x * 2。map对给定的列表（[1; 2; 3]）中的每个元素调用double，产生了这个结果：一个新的列表，其中每个数字都变成了原来的两倍。
我们已经知道map是一个高阶函数（higher-order function，简称HOF）。高阶函数就是说这个函数可以用另一个函数作为它的一个参数，听起来很深奥的说法。
目前来说这个概念还很简单。如果你熟悉C/C++，就会觉得它看上去好像就是传递一个函数指针。Java则有种叫做匿名类的讨厌东西，类似于一种迟钝的、冗长的闭包。如果你了解Perl，那么你可能已经知道并正在使用Perl的闭包以及Perl的map函数，它就是我们正在讨论的东西。实际上Perl也是一个很好的函数式语言。
闭包（Closure）指携带着它们被定义所处的“环境”的函数。特别地说，一个闭包可以引用在它定义时可用的那些变量。下面我们来泛化前面的函数，使得函数可以输入任何整数列表并将每个元素乘以一个任意值n：
let multiply n list =
  let f x =
    n [...]]]></description>
			<content:encoded><![CDATA[<h2><a id="What_is_functional_programming_" name="What_is_functional_programming_">什么是函数式编程</a></h2>
<p class="first_para">我们已经在本教程中学了有一段时间了，然而我们还没有真正考虑过<strong>函数式编程</strong>（functional programming）。目前文中讲述的一系列特点——丰富的数据类型、模式匹配、类型推断、嵌套函数——这些你只能想像存在于某种“超级C”语言中。有了这些神奇特点之后，就能让你的代码更精炼、更容易阅读并且错误更少，但但实际上它们和函数式编程的关系却不是很大。事实上我要说的观点是函数式语言如此神奇<em>并非</em>是因为其函数式编程，而是因为我们长时间局限于类C语言之中，而同时编程的界限却在不断地继续扩展。所以当我们在第N次重复写<code>struct { int type; union { ... } }</code>的时候，ML和Haskell程序员已经可以对数据类型使用安全变体和模式匹配了。当我们还在小心翼翼地<code>free</code>每个我们所<code>malloc</code>的东西时，自从80年代就已经有能比手工编码更好的垃圾收集器了。</p>
<p>好吧，说完这些之后，我就可以告诉你什么是函数式编程了。</p>
<p>最基本的定义为（不过不是很让人明白的）：在<strong>函数式语言</strong>中，<strong>函数</strong>是第一等公民。</p>
<p>光说不练，难以令人理解，所以先看一个例子：</p>
<p><pre class="ocaml"># <span style="color: #06c; font-weight: bold;">let</span> double x =
    x * <span style="color: #c6c;">2</span>
  <span style="color: #06c; font-weight: bold;">in</span>
  <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html"><span style="">List</span></a>.<span style="color: #060;">map</span> double <span style="color: #6c6;">&#91;</span> <span style="color: #c6c;">1</span>; <span style="color: #c6c;">2</span>; <span style="color: #c6c;">3</span> <span style="color: #6c6;">&#93;</span>;;
- : int list = <span style="color: #6c6;">&#91;</span><span style="color: #c6c;">2</span>; <span style="color: #c6c;">4</span>; <span style="color: #c6c;">6</span><span style="color: #6c6;">&#93;</span></pre></p>
<p class="first_para">在这个例子中，我首先定义了一个叫做<code>double</code>嵌套函数，输入一个参数<code>x</code>并返回<code>x * 2</code>。<code>map</code>对给定的列表（<code>[1; 2; 3]</code>）中的每个元素调用<code>double</code>，产生了这个结果：一个新的列表，其中每个数字都变成了原来的两倍。</p>
<p>我们已经知道<code>map</code>是一个<strong>高阶函数</strong>（higher-order function，简称HOF）。高阶函数就是说这个函数可以用另一个函数作为它的一个参数，听起来很深奥的说法。</p>
<p>目前来说这个概念还很简单。如果你熟悉C/C++，就会觉得它看上去好像就是传递一个函数指针。Java则有种叫做匿名类的讨厌东西，类似于一种迟钝的、冗长的闭包。如果你了解Perl，那么你可能已经知道并正在使用Perl的闭包以及Perl的<code>map</code>函数，它就是我们正在讨论的东西。实际上Perl也是一个很好的函数式语言。</p>
<p><strong>闭包</strong>（Closure）指携带着它们被定义所处的“环境”的函数。特别地说，一个闭包可以引用在它定义时可用的那些变量。下面我们来泛化前面的函数，使得函数可以输入任何整数列表并将每个元素乘以一个任意值<code>n</code>：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> multiply n list =
  <span style="color: #06c; font-weight: bold;">let</span> f x =
    n * x
  <span style="color: #06c; font-weight: bold;">in</span>
  <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html"><span style="">List</span></a>.<span style="color: #060;">map</span> f list
  ;;</pre></p>
<p class="first_para">因此：</p>
<p><pre class="ocaml"># multiply <span style="color: #c6c;">2</span> <span style="color: #6c6;">&#91;</span><span style="color: #c6c;">1</span>; <span style="color: #c6c;">2</span>; <span style="color: #c6c;">3</span><span style="color: #6c6;">&#93;</span>;;
- : int list = <span style="color: #6c6;">&#91;</span><span style="color: #c6c;">2</span>; <span style="color: #c6c;">4</span>; <span style="color: #c6c;">6</span><span style="color: #6c6;">&#93;</span>
# multiply <span style="color: #c6c;">5</span> <span style="color: #6c6;">&#91;</span><span style="color: #c6c;">1</span>; <span style="color: #c6c;">2</span>; <span style="color: #c6c;">3</span><span style="color: #6c6;">&#93;</span>;;
- : int list = <span style="color: #6c6;">&#91;</span><span style="color: #c6c;">5</span>; <span style="color: #c6c;">10</span>; <span style="color: #c6c;">15</span><span style="color: #6c6;">&#93;</span></pre></p>
<p class="first_para"><code>multiply</code>中需要注意的重点是嵌套函数<code>f</code>。这是一个闭包。看一下<code>f</code>是如何使用<code>n</code>的值的，它并未实际作为一个明确的传递给<code>f</code>，<code>f</code>而是直接从它的环境中获取了<code>n</code>的值——它是<code>multiply</code>函数的参数，因此在其中是可用的。</p>
<p>听起来可能很直观，不过让我们再仔细看一下对映射的调用：<code>List.map f list</code>。</p>
<p><code> map</code>是定义在<code>List</code>模块中的，和当前的代码并不在一起。换句话说，我们将<code>f</code>传递到一个“很久很久以前，在一个遥远的星系中”定义的模块。就我们所知而言，代码可以将<code>f</code>传递到其他模块，或者将<code>f</code>的引用保存在某处等待以后调用。无论怎么做，闭包都会确保<code>f</code>一定可以访问其来源的环境，并获取<code>n</code>。</p>
<p>下面是从lablgtk中截取的实际的例子。它其实是一个类的方法（我们还没讨论过类和方法，现在只要将其认为是一个函数定义就行了）。</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">class</span> html_skel obj = object <span style="color: #6c6;">&#40;</span>self<span style="color: #6c6;">&#41;</span>
  ...
  ...
  <span style="color: #06c; font-weight: bold;">method</span> save_to_channel chan =
    <span style="color: #06c; font-weight: bold;">let</span> receiver_fn content =
      <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALoutput_string"><span style="">output_string</span></a> chan content;
      <span style="color: #06c; font-weight: bold;">true</span>
    <span style="color: #06c; font-weight: bold;">in</span>
    save obj receiver_fn</pre></p>
<p class="first_para">首先，你要知道在这个方法最后调用的<code>save</code>函数，其第二个参数是一个函数（<code>receiver_fn</code>）。它再重复调用<code>receiver_fn</code>，将来自部件的文本片断储存起来。</p>
<p>现在看一下<code>recevier_fn</code>的定义。这个函数正是一个闭包因为它保存了一个从其环境中引入的<code>chan</code>的引用。</p>
<h3>部分函数的应用以及柯里化</h3>
<p class="first_para">让我们定义一个将两数相加的加法函数：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> plus a b =
  a + b
  ;;</pre></p>
<p class="first_para">下面给在教室后面睡觉的家伙们一些问题：</p>
<ol>
<li><code>plus</code>是什么？</li>
<li><code>plus 2 3</code>是什么？</li>
<li><code>plus 2</code>是什么？</li>
</ol>
<p class="first_para">问题 1 很简单。<code>plus</code>是一个函数，它接受两个整数参数并返回一个整数。类型是这么写的： </p>
<pre>plus : int -&gt; int -&gt; int
</pre>
<p class="first_para">问题 2 就更简单了。<code>plus 2 3</code>是一个数字，整数<code>5</code>。类型是这么写的：</p>
<pre>5 : int
</pre>
<p class="first_para">但问题 3 怎么回答呢？貌似<code>plus 2</code>是一个错误。然而，实际上，并非如此。如果我们在OCaml的顶层输入这个表达式，那么它会告诉我们：</p>
<pre># plus 2;;
- : int -&gt; int = &lt;fun&gt;
</pre>
<p class="first_para">这不是一个错误。它告诉我们<code>plus 2</code>实际上是一个<em>函数</em>，它接受一个<code>int</code>并返回一个<code>int</code>。这是怎样的一个函数呢？首先我们给这个函数起个名字叫做（<code>f</code>），然后再进行一些实验，给它一些整数看看会发生什么：</p>
<p><pre class="ocaml"># <span style="color: #06c; font-weight: bold;">let</span> f = plus <span style="color: #c6c;">2</span>;;
<span style="color: #06c; font-weight: bold;">val</span> f : int -&gt; int = &lt;fun&gt;
# f <span style="color: #c6c;">10</span>;;
- : int = <span style="color: #c6c;">12</span>
# f <span style="color: #c6c;">15</span>;;
- : int = <span style="color: #c6c;">17</span>
# f <span style="color: #c6c;">99</span>;;
- : int = <span style="color: #c6c;">101</span></pre></p>
<p class="first_para">在工程中，我们有<a href="http://www.princeton.edu/%7Esacm/humor/proof.html" class="external" title="http://www.princeton.edu/~sacm/humor/proof.html">足够的证据</a>说<code>plus 2</code>就是将2加上另一个数的函数。</p>
<p>回到原来的定义，让我们“填入”第一个参数（<code>a</code>）2，则获得了：</p>
<pre>let plus 2 b =       (* 这不是真正的OCaml代码! *)
  2 + b
  ;;
</pre>
<p class="first_para">我希望你可以了解为何<code>plus 2</code>就是一个函数。</p>
<p>看一下这些表达式的类型也许就能够一窥函数类型中用到的奇怪的-&gt;箭头记号的原理：</p>
<pre>    plus : int -&gt; int -&gt; int
  plus 2 : int -&gt; int
plus 2 3 : int
</pre>
<p class="first_para">这个过程称之为<strong>currying</strong>（柯里化，也可能叫做<strong>uncurrying</strong>反柯里化，我至今也搞不清哪个是哪个）。它之所以如此命名是为了纪念Haskell Curry，他对lambda算子做出了一些相关的重要贡献。由于我要尽可能回避在OCaml背后的数学原理——因为这十分冗长也不切主题——所以这个问题上我就不深入了。如果你对此感兴趣，你可以通过<a href="http://www.google.com/search?q=currying" class="external" title="http://www.google.com/search?q=currying">Google搜索</a>来查找更多关于柯里化的更多信息。</p>
<p>还记得我们前面的<code>double</code>和<code>multiply</code>函数吗？<code>multiply</code>的定义是这样的：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> multiply n list =
  <span style="color: #06c; font-weight: bold;">let</span> f x =
    n * x
  <span style="color: #06c; font-weight: bold;">in</span>
  <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html"><span style="">List</span></a>.<span style="color: #060;">map</span> f list
  ;;</pre></p>
<p class="first_para">现在我们来定义<code>double</code>、<code>triple</code>，这些函数很好写，如下：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> double = multiply <span style="color: #c6c;">2</span>;;
<span style="color: #06c; font-weight: bold;">let</span> triple = multiply <span style="color: #c6c;">3</span>;;</pre></p>
<p class="first_para">它们其实都是函数，看：</p>
<pre># double [1; 2; 3];;
- : int list = [2; 4; 6]
# triple [1; 2; 3];;
- : int list = [3; 6; 9]
</pre>
<p class="first_para">你也可以像这样直接使用部分应用（无需中间的<code>f</code>函数）</p>
<pre># let multiply n = List.map (( * ) n);;
val multiply : int -&gt; int list -&gt; int list = &lt;fun&gt;
# let double = multiply 2;;
val double : int list -&gt; int list = &lt;fun&gt;

# let triple = multiply 3;;
val triple : int list -&gt; int list = &lt;fun&gt;
# double [1; 2; 3];;
- : int list = [2; 4; 6]
# triple [1; 2; 3];;
- : int list = [3; 6; 9]
</pre>
<p class="first_para">在上面的例子中，<code>(( * ) n)</code>是<code>( * )</code>（乘法）函数的部分应用。注意空格是必须的，这样OCaml才不会认为<code>(*</code>是一个注释的开始。</p>
<p>你可以将中缀操作符放入括号中来定义函数。下面是定义的和前面的<code>plus</code>函数完全一样：</p>
<pre># let plus = (+);;
val plus : int -&gt; int -&gt; int = &lt;fun&gt;
# plus 2 3;;
- : int = 5
</pre>
<p class="first_para">下面还有一些有趣的柯理化：</p>
<pre># List.map (plus 2) [1; 2; 3];;
- : int list = [3; 4; 5]
# let list_of_functions = List.map plus [1; 2; 3];;
val list_of_functions : (int -&gt; int) list = [&lt;fun&gt;; &lt;fun&gt;; &lt;fun&gt;]
</pre>
<h3>函数式编程的优势是什么？</h3>
<p class="first_para">函数式编程，和其他的优秀编程技术一样，它也是你的锦囊中用于解决某几类问题的有效工具。对于设计回调函数——它用多种用户，从GUI到事件驱动的循环——十分方便。对于表达泛型算法也十分好用。<code>List.map</code>就是一个泛型算法，用于将函数应用于任何类型的列表。类似的，你还可以定义处理树的泛型函数。某几种类型的数字问题也可以利用函数式编程更快地解决（例如，用数字计算数学函数派生出来的东西）。</p>
<h3>纯粹的和不纯粹的函数式编程</h3>
<p class="first_para">一个<strong>纯粹的函数</strong>是指没有任何<strong>副作用</strong>的函数。副作用其实是指函数在其内部保存某种隐藏的状态。C中，<code>strlen</code>是一个纯函数的很好的例子。如果你对同样的字符串多次调用<code>strlen</code>，它总是返回同样的长度值。<code>strlen</code>的输出（长度）仅由其输入（字符串）决定，不依赖于任何其他东西。但不幸的是，C中很多函数都是不纯的。例如，<code>malloc</code>——如果你用同样的数字对其进行调用，它肯定都不会返回同样的指针给你。<code>malloc</code>当然还依赖于很多隐藏的内部状态（堆上分配的对象、使用的分配方法、从操作系统抓取页，等等）。</p>
<p>ML派生的语言，如OCaml，是“近乎纯粹的”。它们允许通过像引用和数组这类的东西产生一些副作用，但是大部分你写出来的代码都会是纯函数式的因为它们鼓励这种思考方式。Haskell——另一种函数式语言——则是完全纯函数式的。因为写不纯的函数有时候更加有用和有效，所以OCaml更加实用的。</p>
<p>使用纯函数还有一些理论上的好处。其中一个好处是，如果某个函数是纯粹的，那么如果使用同样的参数对其调用多次的话，编译器就只需要调用该函数一次。在C中有一个很好的例子：</p>
<p><pre class="c"><span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>i = <span style="color: #cc66cc;">0</span>; i &lt; strlen <span style="color: #66cc66;">&#40;</span>s<span style="color: #66cc66;">&#41;</span>; ++i<span style="color: #66cc66;">&#41;</span>
  <span style="color: #66cc66;">&#123;</span>
    <span style="color: #808080; font-style: italic;">// 做一些不影响s的事情</span>
  <span style="color: #66cc66;">&#125;</span></pre></p>
<p class="first_para">如果就这样编译了，那么这个循环是O(n<sup>2</sup>)因为每次都要调用<code>strlen (s)</code>然后<code>strlen</code>又需要迭代整个<code>s</code>。如果编译器足够聪明可以推断出<code>strlen</code>是一个纯函数<em>同时</em><code>s</code>又没有在循环中更新过，那么它就可以删除冗余的<code>strlen</code>的调用，就能使函数变为O(n)复杂度。那么编译器真的能这么做吗？在<code>strlen</code>的情况下，可以，而在其他情况下，可能就不行了。</p>
<p>集中于写短小的纯函数可以让你使用一种自地向上的方式来构建可复用的代码，同时边继续边测试每个小函数。而当前时尚的方式是使用一种自顶向下的方式来仔细设计你的程序，不过在作者的经历中，这往往会导致项目失败。</p>
<h3>严格性和惰性</h3>
<p class="first_para">C派生的和ML派生的语言都是严格的。Haskell和Miranda则是非严格的，或者说是惰性的。OCaml默认是严格的，不过当必须时也可以进行惰性风格的编程。</p>
<p>在严格语言中，给函数传递参数的时候都是先计算好的，然后把结果传递给函数。例如，在严格语言中，下面的调用肯定会导致“被零除”的错误：</p>
<p><pre class="ocaml">give_me_a_three <span style="color: #6c6;">&#40;</span><span style="color: #c6c;">1</span>/<span style="color: #c6c;">0</span><span style="color: #6c6;">&#41;</span>;;</pre></p>
<p class="first_para">如果你用一些常见的语言编程的话，这就是其工作的方式，如果它能以任何方式运行起来的话，你一定十分惊讶。</p>
<p>在一个惰性语言中，就会有一些其他奇怪的事情发生。传递给函数的参数只有当函数实际用到它们的时候才会进行计算。还记得前面<code>give_me_a_three</code>函数会抛弃它的参数，总是返回3么？在惰性语言中，上面的调用并<em>不会</em>失败，因为<code>give_me_a_three</code>从不会看它第一个参数，所以第一个参数并不会被计算，所以被零除并不会发生。</p>
<p>惰性语言还能让你做一些很古怪的事情，比如定义一个无限长的列表。前提是你不会真的去迭代整个列表，这就没问题（换句话说，比如你只要获取前10个元素）。</p>
<p>OCaml是一个严格语言，不过它有一个<code>Lazy</code>模块可以让你写一些惰性表达式。下面有一个例子。首先我们给<code>1/0</code>创建一个惰性表达式：</p>
<pre># let lazy_expr = lazy (1/0);;
val lazy_expr : int lazy_t = &lt;lazy&gt;
</pre>
<p class="first_para">注意这种惰性表达式的类型是<code>int lazy_t</code>。</p>
<p>因为<code>give_me_a_three</code>接受<code>'a</code>（任何类型）作为参数，所以我们可以将惰性表达式传递给该函数：</p>
<pre># give_me_a_three lazy_expr;;
- : int = 3
</pre>
<p class="first_para">如果要计算一个惰性表达式，必须使用<code>Lazy.force</code>函数：</p>
<p><pre class="ocaml"># <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Lazy.html"><span style="">Lazy</span></a>.<span style="color: #060;">force</span> lazy_expr;;
<span style="color: #06c; font-weight: bold;">Exception</span>: <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#EXCEPTIONDivision_by_zero"><span style="">Division_by_zero</span></a>.</pre></p>
<h3>装箱类型和拆箱类型</h3>
<p class="first_para">当讨论函数式语言的时候，有一个术语你会经常听到，这就是“装箱”。当我第一次听到这个术语的时候，我也很困惑，其实如果你以前用过C/C++或者Java，那么对你来说装箱类型和拆箱类型之间的区别是相当简单的（在Perl中，一切东西都是被装箱过的）。</p>
<p>如何去思考一个被装箱的对象呢，在C中这种对象就是使用<code>malloc</code>在堆上分配的（或者在C++中等同于<code>new</code>），同时/或者通过一个指针来引用的对象。看一下这个C程序的例子：</p>
<p><pre class="c"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #993333;">void</span>
printit <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> *ptr<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
  <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;the number is %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, *ptr<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span>
main <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
  <span style="color: #993333;">int</span> a = <span style="color: #cc66cc;">3</span>;
  <span style="color: #993333;">int</span> *p = &amp;a;
&nbsp;
  printit <span style="color: #66cc66;">&#40;</span>p<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></p>
<p class="first_para">变量<code>a</code>是分配在栈上的，所以肯定是被拆箱过的。</p>
<p>函数<code>printit</code>接受一个装箱过的整数并将其打印出来。</p>
<p>下面的图像是了一组拆箱（上部）和装箱（下部）整数之间的对比：</p>
<p><a class="image_not_found" href="/_bin/upload_image_form.cmo?name=boxedarray.png">boxedarray.png</a></p>
<p>拆箱了的整数要比装箱了的快很多。另外，因为单独分配更少，所以对于拆箱的对象的类型垃圾收集更加快速也更加简单。</p>
<p>在C/C++中，你应该对构造以上两种类型的数组是没有问题的。在Java中，有两种类型，<code>int</code>是拆箱型的，而<code>Integer</code>是装箱型的，因此相对不如前者有效。在OCaml中，所有的基本类型都是拆箱型的。</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nirvanastudio.org/ocaml/functional-programming.html/feed</wfw:commentRss>
		</item>
		<item>
		<title>FireBug 控制台函数说明</title>
		<link>http://www.nirvanastudio.org/javascript/firebug-%e6%8e%a7%e5%88%b6%e5%8f%b0%e5%87%bd%e6%95%b0%e8%af%b4%e6%98%8e.html</link>
		<comments>http://www.nirvanastudio.org/javascript/firebug-%e6%8e%a7%e5%88%b6%e5%8f%b0%e5%87%bd%e6%95%b0%e8%af%b4%e6%98%8e.html#comments</comments>
		<pubDate>Wed, 20 Sep 2006 02:25:25 +0000</pubDate>
		<dc:creator>Nicholas Ding</dc:creator>
		
		<category><![CDATA[Ajax]]></category>

		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[Web??]]></category>

		<guid isPermaLink="false">http://www.nirvanastudio.org/news/firebug-%e6%8e%a7%e5%88%b6%e5%8f%b0%e5%87%bd%e6%95%b0%e8%af%b4%e6%98%8e.html</guid>
		<description><![CDATA[原文地址：http://www.joehewitt.com/software/firebug/docs.php

FireBug 是一个非常实用的JavaScript以及DOM查看调试工具，是 Firefox 的一个插件。使用 FireBug 调试 AJAX 应用非常方便，终于可以告别 alert 时代了！

Console Logging 函数
FireBug 为所有 Web 页面提供了一个 console 对象。这个对象有以下函数：
Logging 基础
console.log(&#8221;message&#8221; [,objects]) - 将一个字符串打印到控制台。字符串可以包含任何“String Formatting”小节描述的模式。字符串后面的对象应该用来取代之前字符串中的模式。（译者注：大家用过C里面 printf 吧，效果基本是一样的。）
Logging 等级
通常根据不同的等级来区分Logging的严重程度是很有帮助的。FireBug 提供了4个等级。为了达到视觉分离的效果，这些函数与 log 不同的地方就是它们在被调用的时候会自动包含一个指向代码行数的链接。
console.debug(&#8221;message&#8221; [,objects]) - 记录一个 debug 消息。
console.info(&#8221;message&#8221; [,objects]) - 记录一个信息.
console.warn(&#8221;message&#8221; [,objects]) - 记录一个警告.
console.error(&#8221;message&#8221; [,objects]) - 记录一个错误.
断言
断言是一条确保代码规则的非常好的途径。console 对象包含了一系列各种类型的断言函数，并且允许你编写自己的断言函数。
console.assert(a, &#8220;message&#8221; [,objects]) - Asserts that an a is true.
console.assertEquals(a, b, &#8220;message&#8221; [,objects]) [...]]]></description>
			<content:encoded><![CDATA[<p>原文地址：<a href="http://www.joehewitt.com/software/firebug/docs.php">http://www.joehewitt.com/software/firebug/docs.php</a></p>
<blockquote><p>
<a href="http://www.joehewitt.com/software/firebug/">FireBug</a> 是一个非常实用的JavaScript以及DOM查看调试工具，是 Firefox 的一个插件。使用 FireBug 调试 AJAX 应用非常方便，终于可以告别 alert 时代了！
</p></blockquote>
<h2>Console Logging 函数</h2>
<p>FireBug 为所有 Web 页面提供了一个 console 对象。这个对象有以下函数：</p>
<h3>Logging 基础</h3>
<div><b>console.log(&#8221;message&#8221; [,objects])</b> - 将一个字符串打印到控制台。字符串可以包含任何“String Formatting”小节描述的模式。字符串后面的对象应该用来取代之前字符串中的模式。（译者注：大家用过C里面 printf 吧，效果基本是一样的。）</div>
<h3>Logging 等级</h3>
<p>通常根据不同的等级来区分Logging的严重程度是很有帮助的。FireBug 提供了4个等级。为了达到视觉分离的效果，这些函数与 <code>log</code> 不同的地方就是它们在被调用的时候会自动包含一个指向代码行数的链接。</p>
<div><b>console.debug(&#8221;message&#8221; [,objects])</b> - 记录一个 debug 消息。</div>
<div><b>console.info(&#8221;message&#8221; [,objects])</b> - 记录一个信息.</div>
<div><b>console.warn(&#8221;message&#8221; [,objects])</b> - 记录一个警告.</div>
<div><b>console.error(&#8221;message&#8221; [,objects])</b> - 记录一个错误.</div>
<h3>断言</h3>
<p>断言是一条确保代码规则的非常好的途径。console 对象包含了一系列各种类型的断言函数，并且允许你编写自己的断言函数。</p>
<div><b>console.assert(a, &#8220;message&#8221; [,objects])</b> - Asserts that an <code>a</code> is true.</div>
<div><b>console.assertEquals(a, b, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is equal to <code>b</code>.</div>
<div><b>console.assertNotEquals(a, b, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is not equal to <code>b</code>.</div>
<div><b>console.assertGreater(a, b, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is greater than <code>b</code>.</div>
<div><b>console.assertNotGreater(a, b, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is not greater than <code>b</code>.</div>
<div><b>console.assertLess(a, b, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is less than <code>b</code>.</div>
<div><b>console.assertNotLess(a, b, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is not less than <code>b</code>.</div>
<div><b>console.assertContains(a, b, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is in the array <code>b</code>.</div>
<div><b>console.assertNotContains(a, b, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is not in the array <code>b</code>.</div>
<div><b>console.assertTrue(a, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is equal to <code>true</code>.</div>
<div><b>console.assertFalse(a, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is equal to <code>false</code>.</div>
<div><b>console.assertNull(a, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is equal to <code>null</code>.</div>
<div><b>console.assertNotNull(a, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is not equal to <code>null</code>.</div>
<div><b>console.assertUndefined(a, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is equal to <code>undefined</code>.</div>
<div><b>console.assertNotUndefined(a, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is not equal to <code>undefined</code>.</div>
<div><b>console.assertInstanceOf(a, b, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is an instance of type <code>b</code>.</div>
<div><b>console.assertNotInstanceOf(a, b, &#8220;message&#8221; [,objects])</b> - Asserts that <code>a</code> is not an instance of type <code>b</code>.</div>
<div><b>console.assertTypeOf(a, b, &#8220;message&#8221; [,objects])</b> - Asserts that the type of <code>a</code> is equal to the string <code>b</code>.</div>
<div><b>console.assertNotTypeOf(a, b, &#8220;message&#8221; [,objects])</b> - Asserts that the type of <code>a</code> is not equal to the string <code>b</code>.</div>
<h3>测量（Measurement）</h3>
<p>下面的一些函数可以让你方便的测量你的一些代码。</p>
<div><b>console.trace()</b> - 记录执行点的堆栈信息。</div>
<div><b>console.time(&#8221;name&#8221;)</b> - 根据 name 创建一个唯一的计时器。</div>
<div><b>console.timeEnd(&#8221;name&#8221;)</b> - 根据 name 停止计时器，并且记录消耗的时间，以毫秒为单位。</div>
<div><b>console.count(&#8221;name&#8221;)</b> - 记录该行代码执行的次数。</div>
<h2>字符串格式化</h2>
<p>所有 console 的 logging 函数都可以通过以下模式格式化字符串：</p>
<div><b>%s</b> - 将对象格式化为字符串。</div>
<div><b>%d, %i, %l, %f</b> - 将对象格式化为数字。</div>
<div><b>%o</b> - 将对象格式化成一个指向 inspector 的超链接。</div>
<div><b>%1.o, %2.0, etc..</b> - 将对象格式化成包含自己属性的可交互的表格。</div>
<div><b>%.o</b> - 将对象格式化成具有自身属性的一个数组。</div>
<div><b>%x</b> - 将对象格式化成一个可交互的 XML 树形结构。</div>
<div><b>%1.x, %2.x, etc..</b> - 将对象格式化成一个可交互的 XML 数型结构，并且展开 <i>n</i> 层节点。</div>
<p>如果你需要一个真实的 % 符号，你可以通过一个转移符号就像这样 &#8220;\%&#8221;。</p>
<h2>命令行函数</h2>
<p>内建的命令行函数可以通过以下命令行使用：
</p>
<div><b>$(&#8221;id&#8221;)</b> - document.getElementById() 的简写。（译者注：跟 prototype.js 学来的吧？）</div>
<div><b>$$(&#8221;css&#8221;)</b> - 返回一个符合 CSS 选择器的元素数组。</div>
<div><b>$x(&#8221;xpath&#8221;)</b> - 返回一个符合 XPath 选择器的元素数组。</div>
<div><b>$0</b> - 返回最近被检查（inspected）的对象。</div>
<div><b>$1</b> - 返回最近被检查（inspected）的下一个对象。</div>
<div><b>$n(5)</b> - 返回最近被检查的第n个对象。</div>
<div><b>inspect(object)</b> - 将对象显示在 Inspector 中。</div>
<div><b>dir(object)</b> - 返回一个对象的属性名数组。（译者注：跟 Python 学的？）</div>
<div><b>clear()</b> - 清除控制台信息。</div>
]]></content:encoded>
			<wfw:commentRss>http://www.nirvanastudio.org/javascript/firebug-%e6%8e%a7%e5%88%b6%e5%8f%b0%e5%87%bd%e6%95%b0%e8%af%b4%e6%98%8e.html/feed</wfw:commentRss>
		</item>
		<item>
		<title>空指针、断言和警告</title>
		<link>http://www.nirvanastudio.org/ocaml/null-pointers-asserts-and-warnings.html</link>
		<comments>http://www.nirvanastudio.org/ocaml/null-pointers-asserts-and-warnings.html#comments</comments>
		<pubDate>Mon, 11 Sep 2006 06:22:21 +0000</pubDate>
		<dc:creator>ShiningRay</dc:creator>
		
		<category><![CDATA[OCaml]]></category>

		<guid isPermaLink="false">http://www.nirvanastudio.org/ocaml/null-pointers-asserts-and-warnings.html</guid>
		<description><![CDATA[原文地址：http://www.ocaml-tutorial.org/null_pointers,_asserts_and_warnings，翻译：ShiningRay
空指针
那么现在假设你在网站上放了个调查，询问读者的姓名和年龄。有一个问题是，如果由于某些原因一些读者不想给出他们的年龄——他们很顽固，拒绝填写这一栏。那么可怜的数据库管理员要怎么做呢？
假设年龄是由一个int来表示的，有两种方式来解决这个问题。最常见的方式（也是最有问题的）是当没有收集到年龄信息的时候，为年龄假设某种“特殊”的值。所以，假设当没有收集到数据时，年龄为-1，否则当有数据时，则填入年龄（即使它是无效的！）。它暂时完成了工作，直到你要开始对年龄进行计算，例如，计算网站访客的平均年龄。由于你忘了考虑这个特殊值，最后可能访客年龄的平均值为7（？），然后你就会雇佣设计师将长的单词去掉并到处使用简单的色块。
另一种方式，也就是正确的方式是将年龄存储在一个类型为“int或null”的字段中。下面是这个用于存储年龄的SQL表格：
CREATE TABLE users
&#40;
  userid serial,
  name text NOT NULL,
  age int             -- 可以为空
&#41;;
如果没有收集到年龄数据，那么存到数据库中的是一个特殊的SQL NULL值。当你要计算平均值或其他东西的时候，SQL会自动忽略这些空值。
编程语言也支持空值，虽然某些语言中的使用要比其他一些简单。在Perl中，任何量（即数字或者字符串）都可以是undef（空在Perl中的说法）。这是导致很多警告的一个原因，但这些警告往往会被没有经验的程序员所忽略，即便这些警告可能表示严重的错误。在Java中，任何指向对象的引用都可以为空，所以在Java中可以将年龄存为Integer，就能让年龄的引用为null。在C语言中，指针当然能为空，但是如果要让一个简单的整数为空，首先要将其装箱为一个由malloc在堆上分配的对象。
OCaml则有其自己对空值问题的优雅解决方法，使用一个简单的多态变体类型，定义（在Pervasives中的）为：
type 'a option = None &#124; Some of 'a
“空指针”写作None。上面的例子中的年龄的类型（一个可以为空的int）是int option（记住：它是类似于int list和int binary_tree的逆向写法）。
# Some 3;;
- : int option = Some 3
可选int的列表如何：
# &#91; None; Some 3; Some 6; None [...]]]></description>
			<content:encoded><![CDATA[<p>原文地址：<a href="http://www.ocaml-tutorial.org/null_pointers,_asserts_and_warnings">http://www.ocaml-tutorial.org/null_pointers,_asserts_and_warnings</a>，翻译：ShiningRay</p>
<h2><a name="Null_pointers" id="Null_pointers">空指针</a></h2>
<p class="first_para">那么现在假设你在网站上放了个调查，询问读者的姓名和年龄。有一个问题是，如果由于某些原因一些读者不想给出他们的年龄——他们很顽固，拒绝填写这一栏。那么可怜的数据库管理员要怎么做呢？</p>
<p>假设年龄是由一个<code>int</code>来表示的，有两种方式来解决这个问题。最常见的方式（也是最<em>有问题</em>的）是当没有收集到年龄信息的时候，为年龄假设某种“特殊”的值。所以，假设当没有收集到数据时，年龄为-1，否则当有数据时，则填入年龄（即使它是无效的！）。它暂时完成了工作，直到你要开始对年龄进行计算，例如，计算网站访客的平均年龄。由于你忘了考虑这个特殊值，最后可能访客年龄的平均值为7（？），然后你就会雇佣设计师将长的单词去掉并到处使用简单的色块。</p>
<p>另一种方式，也就是正确的方式是将年龄存储在一个类型为“int或null”的字段中。下面是这个用于存储年龄的SQL表格：</p>
<p><pre class="sql"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> users
<span style="color: #66cc66;">&#40;</span>
  userid serial,
  name text <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span>,
  age int             <span style="color: #808080; font-style: italic;">-- 可以为空</span>
<span style="color: #66cc66;">&#41;</span>;</pre></p>
<p class="first_para">如果没有收集到年龄数据，那么存到数据库中的是一个特殊的SQL <code>NULL</code>值。当你要计算平均值或其他东西的时候，SQL会自动忽略这些空值。</p>
<p>编程语言也支持空值，虽然某些语言中的使用要比其他一些简单。在Perl中，任何量（即数字或者字符串）都可以是<code>undef</code>（空在Perl中的说法）。这是导致很多警告的一个原因，但这些警告往往会被没有经验的程序员所忽略，即便这些警告可能表示严重的错误。在Java中，任何指向对象的引用都可以为空，所以在Java中可以将年龄存为<code>Integer</code>，就能让年龄的引用为<code>null</code>。在C语言中，指针当然能为空，但是如果要让一个简单的整数为空，首先要将其装箱为一个由<code>malloc</code>在堆上分配的对象。</p>
<p>OCaml则有其自己对空值问题的优雅解决方法，使用一个简单的多态变体类型，定义（在<code>Pervasives</code>中的）为：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">type</span> 'a <span style="color: #06c; font-weight: bold;">option</span> = None | Some <span style="color: #06c; font-weight: bold;">of</span> 'a</pre></p>
<p class="first_para">“空指针”写作<code>None</code>。上面的例子中的年龄的类型（一个可以为空的<code>int</code>）是<code>int option</code>（记住：它是类似于<code>int list</code>和<code>int binary_tree</code>的逆向写法）。</p>
<p><pre class="ocaml"># Some <span style="color: #c6c;">3</span>;;
- : int <span style="color: #06c; font-weight: bold;">option</span> = Some <span style="color: #c6c;">3</span></pre></p>
<p class="first_para">可选int的列表如何：</p>
<p><pre class="ocaml"># <span style="color: #6c6;">&#91;</span> None; Some <span style="color: #c6c;">3</span>; Some <span style="color: #c6c;">6</span>; None <span style="color: #6c6;">&#93;</span>;;
- : int <span style="color: #06c; font-weight: bold;">option</span> list = <span style="color: #6c6;">&#91;</span>None; Some <span style="color: #c6c;">3</span>; Some <span style="color: #c6c;">6</span>; None<span style="color: #6c6;">&#93;</span></pre></p>
<p class="first_para">And what about an optional list of ints?</p>
<p><pre class="ocaml"># Some <span style="color: #6c6;">&#91;</span><span style="color: #c6c;">1</span>; <span style="color: #c6c;">2</span>; <span style="color: #c6c;">3</span><span style="color: #6c6;">&#93;</span>;;
- : int list <span style="color: #06c; font-weight: bold;">option</span> = Some <span style="color: #6c6;">&#91;</span><span style="color: #c6c;">1</span>; <span style="color: #c6c;">2</span>; <span style="color: #c6c;">3</span><span style="color: #6c6;">&#93;</span></pre></p>
<h2><a name="Assert__warnings__fatal_errors__and_printing_to_stderr" id="Assert__warnings__fatal_errors__and_printing_to_stderr">断言、警告、致命错误以及stderr输出</a></h2>
<p class="first_para">Perl的一个很好的特点是有丰富的调试程序和处理异常错误的命令，包括打印栈轨迹、抛出和捕获异常等。OCaml没有这么丰富的调试命令——不过比Java要好一点，基本和C差不多，和Perl比就逊色一些。（在以后我们会更加详细地讨论异常。）</p>
<p>首先，<code>assert</code>输入一个表达式作为参数，并抛出一个异常。假设你没有捕获这个异常（捕获这个异常可能是不太明智的，尤其对于初学者来说），它会导致程序停止并输出发生错误的源文件和行号。例如：</p>
<p><pre class="ocaml"># assert <span style="color: #6c6;">&#40;</span><a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Sys.html"><span style="">Sys</span></a>.<span style="color: #060;">os_type</span> = <span style="color: #3cb371;">&quot;Win32&quot;</span><span style="color: #6c6;">&#41;</span>;;
<span style="color: #06c; font-weight: bold;">Exception</span>: Assert_failure <span style="color: #6c6;">&#40;</span><span style="color: #3cb371;">&quot;&quot;</span>, <span style="color: #c6c;">0</span>, <span style="color: #c6c;">30</span><span style="color: #6c6;">&#41;</span>.</pre></p>
<p class="first_para">（当然，运行在Win32上是不会抛出错误的）</p>
<p>你也可以直接调用<code>assert false</code>来停止程序运行，不过你最好使用<code>failwith</code>。</p>
<p><code>failwith "错误信息"</code>会抛出一个<code>Failure</code>异常，我们再假设你没有捕获它，那么程序就会停止并给出错误信息。<code>failwith</code>常用于模式匹配中，像下面这个例子中：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">match</span> <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Sys.html"><span style="">Sys</span></a>.<span style="color: #060;">os_type</span> <span style="color: #06c; font-weight: bold;">with</span>
    <span style="color: #3cb371;">&quot;Unix&quot;</span> | <span style="color: #3cb371;">&quot;Cygwin&quot;</span> -&gt;   <span style="color: #5d478b; font-style: italic;">(* 代码省略 *)</span>
  | <span style="color: #3cb371;">&quot;Win32&quot;</span> -&gt;             <span style="color: #5d478b; font-style: italic;">(* 代码省略 *)</span>
  | <span style="color: #3cb371;">&quot;MacOS&quot;</span> -&gt;             <span style="color: #5d478b; font-style: italic;">(* 代码省略*)</span>
  | _ -&gt; <span style="color: #06c; font-weight: bold;">failwith</span> <span style="color: #3cb371;">&quot;this system is not supported&quot;</span></pre></p>
<p class="first_para">注意在这个例子中有两个特别的模式匹配。一个是所谓的“范围模式”用于匹配<code>"Unix"</code>或者<code>"Cygwin"</code>，还有一个是特殊的<code>_</code>模式，用于匹配“任何其他东西”。</p>
<p>如果你要调试程序的话，那么你就可能想要通过某种方式从函数中输出一个警告。下面有一个例子（注意红色高亮部分）：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">open</span> <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Graphics.html"><span style="">Graphics</span></a>;;
&nbsp;
open_graph <span style="color: #3cb371;">&quot; 640x480&quot;</span>;;
<span style="color: #06c; font-weight: bold;">for</span> i = <span style="color: #c6c;">12</span> <span style="color: #06c; font-weight: bold;">downto</span> <span style="color: #c6c;">1</span> <span style="color: #06c; font-weight: bold;">do</span>
  <span style="color: #06c; font-weight: bold;">let</span> radius = i * <span style="color: #c6c;">20</span> <span style="color: #06c; font-weight: bold;">in</span>
  <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALprerr_endline"><span style="">prerr_endline</span></a> <span style="color: #6c6;">&#40;</span><span style="color: #3cb371;">&quot;radius is &quot;</span> ^ <span style="color: #6c6;">&#40;</span><a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALstring_of_int"><span style="">string_of_int</span></a> radius<span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span>;
  set_color <span style="color: #6c6;">&#40;</span><span style="color: #06c; font-weight: bold;">if</span> <span style="color: #6c6;">&#40;</span>i <span style="color: #06c; font-weight: bold;">mod</span> <span style="color: #c6c;">2</span><span style="color: #6c6;">&#41;</span> = <span style="color: #c6c;">0</span> <span style="color: #06c; font-weight: bold;">then</span> red <span style="color: #06c; font-weight: bold;">else</span> yellow<span style="color: #6c6;">&#41;</span>;
  fill_circle <span style="color: #c6c;">320</span> <span style="color: #c6c;">240</span> radius
<span style="color: #06c; font-weight: bold;">done</span>;;
<a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALread_line"><span style="">read_line</span></a> <span style="color: #6c6;">&#40;</span><span style="color: #6c6;">&#41;</span>;;</pre></p>
<p class="first_para">如果你偏爱C风格的<code>printf</code>，那么可以尝试OCaml的<code>Printf</code>模块：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">open</span> <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Graphics.html"><span style="">Graphics</span></a>;;
<span style="color: #06c; font-weight: bold;">open</span> <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Printf.html"><span style="">Printf</span></a>;;
&nbsp;
open_graph <span style="color: #3cb371;">&quot; 640x480&quot;</span>;;
<span style="color: #06c; font-weight: bold;">for</span> i = <span style="color: #c6c;">12</span> <span style="color: #06c; font-weight: bold;">downto</span> <span style="color: #c6c;">1</span> <span style="color: #06c; font-weight: bold;">do</span>
  <span style="color: #06c; font-weight: bold;">let</span> radius = i * <span style="color: #c6c;">20</span> <span style="color: #06c; font-weight: bold;">in</span>
  eprintf <span style="color: #3cb371;">&quot;radius is %d\n&quot;</span> radius;
  set_color <span style="color: #6c6;">&#40;</span><span style="color: #06c; font-weight: bold;">if</span> <span style="color: #6c6;">&#40;</span>i <span style="color: #06c; font-weight: bold;">mod</span> <span style="color: #c6c;">2</span><span style="color: #6c6;">&#41;</span> = <span style="color: #c6c;">0</span> <span style="color: #06c; font-weight: bold;">then</span> red <span style="color: #06c; font-weight: bold;">else</span> yellow<span style="color: #6c6;">&#41;</span>;
  fill_circle <span style="color: #c6c;">320</span> <span style="color: #c6c;">240</span> radius
<span style="color: #06c; font-weight: bold;">done</span>;;
<a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALread_line"><span style="">read_line</span></a> <span style="color: #6c6;">&#40;</span><span style="color: #6c6;">&#41;</span>;;</pre></p>
]]></content:encoded>
			<wfw:commentRss>http://www.nirvanastudio.org/ocaml/null-pointers-asserts-and-warnings.html/feed</wfw:commentRss>
		</item>
		<item>
		<title>数据类型和匹配</title>
		<link>http://www.nirvanastudio.org/ocaml/data-types-and-matching.html</link>
		<comments>http://www.nirvanastudio.org/ocaml/data-types-and-matching.html#comments</comments>
		<pubDate>Sun, 10 Sep 2006 14:53:23 +0000</pubDate>
		<dc:creator>ShiningRay</dc:creator>
		
		<category><![CDATA[OCaml]]></category>

		<guid isPermaLink="false">http://www.nirvanastudio.org/ocaml/data-types-and-matching.html</guid>
		<description><![CDATA[原文地址：http://www.ocaml-tutorial.org/data_types_and_matching 翻译：ShiningRay
链表（Linked List）
和Perl一样，OCaml也将对列表的支持直接内建在语言中了。OCaml中一个列表的所有元素的类型必须一致。使用以下格式来写列表：
&#91;1; 2; 3&#93;
（注意是分号，不是逗号）。
[] 表示空列表。
一个列表有一个“头”（第一个元素）和一个“尾”（剩下的元素）。头是一个元素，而尾则是一个列表，所以前面的例子中，表头是整数1，而表尾是list[2; 3]。
另一种做法是使用cons操作符——头 :: 尾。所以下面的列表写法是完全一样的：
&#91;1; 2; 3&#93;
1 :: &#91;2; 3&#93;
1 :: 2 :: &#91;3&#93;
1 :: 2 :: 3 :: &#91;&#93;
为什么我要提到cons操作符呢？其实，当我们对列表使用模式匹配的时候，它是相当有用的，下面我说详细说明。
链表的类型
整数链表的类型是int list，一般来说，foo类型的链表的类型就是foo list。
由此可以看出，链表的所有元素都必须是同一种类型的。但是类型却可以是多态的（即，'a list），当你要写操作&#34;lists of anything&#34;（任意类型的列表）的泛型函数时，这就相当有用了（注意，'a list 并不代表每个单独的元素可以有不同的类型——所以你还是不能使用它来构造包含混合类型的列表，也就是说，元素的类型可以任意，但所有元素的类型必须相同）。
length函数是定义在OCaml的List模块中的，它是一个很好的例子。它不论列表包含的整数还是字符串或者对象、 还是什么小怪物，List.length函数都可以对其进行处理。因此，List.length的类型是：
List.length : 'a list -&#62; int
结构
C 和 C++都有一个简单的struct的概念，它是结构的缩写。Java中可以使用类来达到类似的效果，虽然费事得多。
考虑以下简单的C结构
struct pair_of_ints &#123;
  int a, b;
&#125;;
在OCaml中，能等同于它的最简单的东西是tuple（元组），诸如(3, 4)，其类型为int * int。与列表不同，元组可以包含不同类型的元素，所以例如(3, &#34;hello&#34;, 'x')的类型为int * string * char。
在OCaml中还有一种稍微复杂一点的写C结构的方法，是使用一个record（记录）。记录，和C结构一样，可以让你对其中的元素进行命名，而无需记住它们出现的顺序。下面是与上面的C结构等同的记录：
type pair_of_ints [...]]]></description>
			<content:encoded><![CDATA[<p>原文地址：<a href="http://www.ocaml-tutorial.org/data_types_and_matching" rel="external">http://www.ocaml-tutorial.org/data_types_and_matching</a> 翻译：<a href="http://wiki.nirvanastudio.org/wiki/ShiningRay">ShiningRay</a></p>
<h2><a name="Linked_lists" id="Linked_lists">链表（Linked List）</a></h2>
<p class="first_para">和Perl一样，OCaml也将对列表的支持直接内建在语言中了。OCaml中一个列表的所有元素的类型必须一致。使用以下格式来写列表：</p>
<p><pre class="ocaml"><span style="color: #6c6;">&#91;</span><span style="color: #c6c;">1</span>; <span style="color: #c6c;">2</span>; <span style="color: #c6c;">3</span><span style="color: #6c6;">&#93;</span></pre></p>
<p class="first_para">（注意是分号，不是逗号）。</p>
<p><code>[]</code> 表示空列表。</p>
<p>一个列表有一个“<strong>头</strong>”（第一个元素）和一个“<strong>尾</strong>”（剩下的元素）。头是一个元素，而尾则是一个列表，所以前面的例子中，表头是整数<code>1</code>，而表尾是<em>list</em><code>[2; 3]</code>。</p>
<p>另一种做法是使用<strong>cons</strong>操作符——<code><em>头</em> :: <em>尾</em></code>。所以下面的列表写法是完全一样的：</p>
<p><pre class="ocaml"><span style="color: #6c6;">&#91;</span><span style="color: #c6c;">1</span>; <span style="color: #c6c;">2</span>; <span style="color: #c6c;">3</span><span style="color: #6c6;">&#93;</span>
<span style="color: #c6c;">1</span> :: <span style="color: #6c6;">&#91;</span><span style="color: #c6c;">2</span>; <span style="color: #c6c;">3</span><span style="color: #6c6;">&#93;</span>
<span style="color: #c6c;">1</span> :: <span style="color: #c6c;">2</span> :: <span style="color: #6c6;">&#91;</span><span style="color: #c6c;">3</span><span style="color: #6c6;">&#93;</span>
<span style="color: #c6c;">1</span> :: <span style="color: #c6c;">2</span> :: <span style="color: #c6c;">3</span> :: <span style="color: #6c6;">&#91;</span><span style="color: #6c6;">&#93;</span></pre></p>
<p class="first_para">为什么我要提到cons操作符呢？其实，当我们对列表使用<em>模式匹配</em>的时候，它是相当有用的，下面我说详细说明。</p>
<h3>链表的类型</h3>
<p class="first_para">整数链表的类型是<code>int list</code>，一般来说，<code>foo</code>类型的链表的类型就是<code>foo list</code>。</p>
<p>由此可以看出，链表的所有元素都必须是同一种类型的。但是类型却可以是多态的（即，<code>'a list</code>），当你要写操作&quot;lists of anything&quot;（任意类型的列表）的泛型函数时，这就相当有用了（注意，<code>'a list</code> 并不代表每个单独的元素可以有不同的类型——所以你还是不能使用它来构造包含混合类型的列表，也就是说，元素的类型可以任意，但所有元素的类型必须相同）。</p>
<p><code>length</code>函数是定义在OCaml的<code>List</code>模块中的，它是一个很好的例子。它不论列表包含的整数还是字符串或者对象、 还是什么小怪物，<code>List.length</code>函数都可以对其进行处理。因此，<code>List.length</code>的类型是：</p>
<p><pre class="ocaml"><a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html"><span style="">List</span></a>.<span style="color: #060;">length</span> : 'a list -&gt; int</pre></p>
<h2><a name="Structures" id="Structures">结构</a></h2>
<p class="first_para">C 和 C++都有一个简单的<code>struct</code>的概念，它是结构的缩写。Java中可以使用类来达到类似的效果，虽然费事得多。</p>
<p>考虑以下简单的C结构</p>
<p><pre class="c"><span style="color: #993333;">struct</span> pair_of_ints <span style="color: #66cc66;">&#123;</span>
  <span style="color: #993333;">int</span> a, b;
<span style="color: #66cc66;">&#125;</span>;</pre></p>
<p class="first_para">在OCaml中，能等同于它的最简单的东西是<strong>tuple</strong>（元组），诸如<code>(3, 4)</code>，其类型为<code>int * int</code>。与列表不同，元组可以包含不同类型的元素，所以例如<code>(3, &quot;hello&quot;, 'x')</code>的类型为<code>int * string * char</code>。</p>
<p>在OCaml中还有一种稍微复杂一点的写C结构的方法，是使用一个<strong>record</strong>（记录）。记录，和C结构一样，可以让你对其中的元素进行命名，而无需记住它们出现的顺序。下面是与上面的C结构等同的记录：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">type</span> pair_of_ints = <span style="color: #6c6;">&#123;</span> a : int; b : int <span style="color: #6c6;">&#125;</span>;;</pre></p>
<p class="first_para">这就可以定义一个类型，那么如何实际<em>创建</em>这种类型的对象呢？</p>
<p><pre class="ocaml"><span style="color: #6c6;">&#123;</span> a=<span style="color: #c6c;">3</span>; b=<span style="color: #c6c;">5</span> <span style="color: #6c6;">&#125;</span></pre></p>
<p class="first_para">注意我们在类型定义中使用了&quot;:&quot;，而在创建这种类型的对象时使用了&quot;=&quot;。</p>
<p>下面是一些例子：</p>
<p><pre class="ocaml"># <span style="color: #06c; font-weight: bold;">type</span> pair_of_ints = <span style="color: #6c6;">&#123;</span> a : int; b : int <span style="color: #6c6;">&#125;</span>;;
<span style="color: #06c; font-weight: bold;">type</span> pair_of_ints = <span style="color: #6c6;">&#123;</span> a : int; b : int; <span style="color: #6c6;">&#125;</span>
# <span style="color: #6c6;">&#123;</span>a=<span style="color: #c6c;">3</span>; b=<span style="color: #c6c;">5</span><span style="color: #6c6;">&#125;</span>;;
- : pair_of_ints = <span style="color: #6c6;">&#123;</span>a = <span style="color: #c6c;">3</span>; b = <span style="color: #c6c;">5</span><span style="color: #6c6;">&#125;</span>
# <span style="color: #6c6;">&#123;</span>a=<span style="color: #c6c;">3</span><span style="color: #6c6;">&#125;</span>;;
Some record field labels are undefined: b</pre></p>
<p class="first_para">所以OCaml不会允许在结构中有未定义的字段。</p>
<h2><a name="Variants__qualified_unions_and_enums_" id="Variants__qualified_unions_and_enums_">变体（条件联合和枚举）</a></h2>
<p class="first_para">C语言中并不直接存在“条件联合”（&quot;qualified union&quot;），虽然gcc编译器中对它有一些支持。 下面是C中使用条件联合的一种模式：</p>
<p><pre class="c"><span style="color: #993333;">struct</span> foo <span style="color: #66cc66;">&#123;</span>
  <span style="color: #993333;">int</span> type;
<span style="color: #339933;">#define TYPE_INT 1</span>
<span style="color: #339933;">#define TYPE_PAIR_OF_INTS 2</span>
<span style="color: #339933;">#define TYPE_STRING 3</span>
  <span style="color: #993333;">union</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #993333;">int</span> i;        <span style="color: #808080; font-style: italic;">// If type == TYPE_INT.</span>
    <span style="color: #993333;">int</span> pair<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#93;</span>;  <span style="color: #808080; font-style: italic;">// If type == TYPE_PAIR_OF_INTS.</span>
    <span style="color: #993333;">char</span> *str;    <span style="color: #808080; font-style: italic;">// If type == TYPE_STRING.</span>
  <span style="color: #66cc66;">&#125;</span> u;
<span style="color: #66cc66;">&#125;</span>;</pre></p>
<p class="first_para">大家应该可以明白，而且它看上去并不太好看。首先，它不安全：程序员可能会犯一个错误，并意外地（假设）当结构中实际存储着字符串的时候调用了<code>u.i</code>字段。同时编译器也不能很容易检查是否所有可能的类型都在switch语句中检验过了（你可以使用一个<code>enum</code>类型来解决这个特殊的问题）。程序员也可能忘记设置<code>type</code>字段，这就可能导致这种奇怪的事情发生。此外，这种模式也很麻烦。</p>
<p>下面是在OCaml中等同于上面的一种优雅并简练的解决方法：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">type</span> foo = Nothing | Int <span style="color: #06c; font-weight: bold;">of</span> int | Pair <span style="color: #06c; font-weight: bold;">of</span> int * int | <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/String.html"><span style="">String</span></a> <span style="color: #06c; font-weight: bold;">of</span> string;;</pre></p>
<p class="first_para">这就是我们所需的类型定义。每个由<code>|</code> 分开的部分的第一个部分称做构造器（constructor）。你可以将其换作任何东西，只要其首字母大写。如果构造器可以用于定义一个值，那么在其后跟上<code>of type</code>部分，这里类型type总是以小写字母开头。在前面的例子中， Nothing被用作一个常量，其他的构造器则用于创建值。</p>
<p>要实际<em>创建</em>这种类型的东西，你可以输入：</p>
<p><pre class="ocaml">Nothing
Int <span style="color: #c6c;">3</span>
Pair <span style="color: #6c6;">&#40;</span><span style="color: #c6c;">4</span>, <span style="color: #c6c;">5</span><span style="color: #6c6;">&#41;</span>
<a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/String.html"><span style="">String</span></a> <span style="color: #3cb371;">&quot;hello&quot;</span>
     &amp;c.</pre></p>
<p class="first_para">其中每个表达式的类型都为<code>foo</code>。</p>
<p>注意当定义类型的时候，使用<code>of</code>，当写该类型的元素的时候则没有。</p>
<p>扩展一下，一个简单的C<code>enum</code>的定义为：</p>
<p><pre class="c"><span style="color: #000000; font-weight: bold;">enum</span> sign <span style="color: #66cc66;">&#123;</span> positive, zero, negative <span style="color: #66cc66;">&#125;</span>;</pre></p>
<p class="first_para">在OCaml中可以写作：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">type</span> sign = Positive | Zero | Negative;;</pre></p>
<h3>递归变体（用于树）</h3>
<p class="first_para">变体也可以是递归的，这也常用于定义树状结构。这就是函数式语言强大表达力之所在：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">type</span> binary_tree = Leaf <span style="color: #06c; font-weight: bold;">of</span> int | Tree <span style="color: #06c; font-weight: bold;">of</span> binary_tree * binary_tree;;</pre></p>
<p class="first_para">以下是一些二叉树。你可以在纸上画一下它们的结构练习一下。</p>
<pre>
Leaf 3
</pre>
<pre>
Tree (Leaf 3, Leaf 4)
</pre>
<pre>

Tree (Tree (Leaf 3, Leaf 4), Leaf 5)
</pre>
<pre>
Tree (Tree (Leaf 3, Leaf 4), Tree (Tree (Leaf 3, Leaf 4), Leaf 5))
</pre>
<h3>参数化变体</h3>
<p class="first_para">上一节中的二叉树每个叶上都是整数，但如果我们只是要描述一个二叉树的<em>形状</em>，而留着以后再确切决定存储何种叶结点，该如何做？这时我们可以使用一个参数化（多态）变体，如下：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">type</span> 'a binary_tree = Leaf <span style="color: #06c; font-weight: bold;">of</span> 'a | Tree <span style="color: #06c; font-weight: bold;">of</span> 'a binary_tree * 'a binary_tree;;</pre></p>
<p class="first_para">这是一个通用类型。在每个叶上都存储了整数的类型称之为<code>int binary_tree</code>。类似的，存储字符串的特定类型称之为<code>string binary_tree</code>。在下面的例子中我们会在OCaml中输入一些实例并让类型推断系统将类型告诉我们：</p>
<p><pre class="ocaml"># Leaf <span style="color: #3cb371;">&quot;hello&quot;</span>;;
- : string binary_tree = Leaf <span style="color: #3cb371;">&quot;hello&quot;</span>
# Leaf <span style="color: #c6c;">3.0</span>;;
- : <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALfloat"><span style="">float</span></a> binary_tree = Leaf <span style="color: #c6c;">3</span>.</pre></p>
<p class="first_para">注意类型的名称是反向的。将它类型名称和列表的类型名称进行一下类比，比如<code>int list</code>等等。</p>
<p>事实上<code>'a list</code>也这样“逆向”写并不是偶然。列表只不过是有着以下一些特殊定义的参数化变体类型：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">type</span> 'a list = <span style="color: #6c6;">&#91;</span><span style="color: #6c6;">&#93;</span> | :: <span style="color: #06c; font-weight: bold;">of</span> 'a * 'a list   <span style="color: #5d478b; font-style: italic;">(* OCaml伪代码 *)</span></pre></p>
<p class="first_para">事实上，上面的定义是不能通过编译的。下面才是等同的有效定义：</p>
<p><pre class="ocaml"># <span style="color: #06c; font-weight: bold;">type</span> 'a list = Nil | :: <span style="color: #06c; font-weight: bold;">of</span> 'a * 'a list;;
<span style="color: #06c; font-weight: bold;">type</span> 'a list = Nil | :: <span style="color: #06c; font-weight: bold;">of</span> 'a * 'a list
# Nil;;
- : 'a list = Nil
# <span style="color: #c6c;">1</span> :: Nil;;
- : int list = :: <span style="color: #6c6;">&#40;</span><span style="color: #c6c;">1</span>, Nil<span style="color: #6c6;">&#41;</span>
# <span style="color: #c6c;">1</span> :: <span style="color: #c6c;">2</span> :: Nil;;
- : int list = :: <span style="color: #6c6;">&#40;</span><span style="color: #c6c;">1</span>, :: <span style="color: #6c6;">&#40;</span><span style="color: #c6c;">2</span>, Nil<span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span></pre></p>
<p class="first_para">记得前面我们说过列表可以有两种写法，使用<code>[1; 2; 3]</code>这样的语法糖或者较为正式的<code>1 :: 2 :: 3 :: []</code>。如果你看懂了上面的<code>'a list</code>的定义，那么你就会明白正规定义的理由和机制了。</p>
<h2><a id="Lists__structures_and_variants___summary" name="Lists__structures_and_variants___summary">列表、结构和变体总结</a></h2>
<pre>
OCaml名称     类型定义例子                使用例子

list            int list                               [1; 2; 3]
tuple           int * string                           (3, &quot;hello&quot;)
record          type pair = { a : int; b : string }    { a = 3; b = &quot;hello&quot; }
variant         type foo = Int of int                  Int 3
                         | Pair of int * string
variant         type sign = Positive | Zero            Positive
                          | Negative                   Zero
parameterised   type 'a my_list = Empty                Cons (1, Cons (2, Empty))
  variant                  | Cons of 'a * 'a my_list
</pre>
<h2><a name="Pattern_matching__on_datatypes_" id="Pattern_matching__on_datatypes_">（数据类型的）模式匹配</a></h2>
<p class="first_para">接下来的函数式编程语言的一个神奇特点是能够解开数据结构并对数据进行模式匹配。这又不是一个真正的“函数式”的特点——你可能知道某些C的变种也可以这么做，不过肯定没有这么神奇。</p>
<p>我们现在一个实际的编程需求开始：我想要将一个简单的像<code>n * (x + y)</code>这样的数学表达式表示为将其中的乘号分开的形式，得到<code>n * x + n * y</code>。</p>
<p>让我们定义满足这些表达式的一个类型：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">type</span> expr = Plus <span style="color: #06c; font-weight: bold;">of</span> expr * expr        <span style="color: #5d478b; font-style: italic;">(* 表示 a + b *)</span>
          | Minus <span style="color: #06c; font-weight: bold;">of</span> expr * expr       <span style="color: #5d478b; font-style: italic;">(* 表示 a - b *)</span>
          | Times <span style="color: #06c; font-weight: bold;">of</span> expr * expr       <span style="color: #5d478b; font-style: italic;">(* 表示 a * b *)</span>
          | Divide <span style="color: #06c; font-weight: bold;">of</span> expr * expr      <span style="color: #5d478b; font-style: italic;">(* 表示 a / b *)</span>
          | Value <span style="color: #06c; font-weight: bold;">of</span> string            <span style="color: #5d478b; font-style: italic;">(* &quot;x&quot;, &quot;y&quot;, &quot;n&quot;, etc. *)</span>
	  ;;</pre></p>
<p class="first_para">表达式<code>n * (x + y)</code>可以写作：</p>
<p><pre class="ocaml">Times <span style="color: #6c6;">&#40;</span>Value <span style="color: #3cb371;">&quot;n&quot;</span>, Plus <span style="color: #6c6;">&#40;</span>Value <span style="color: #3cb371;">&quot;x&quot;</span>, Value <span style="color: #3cb371;">&quot;y&quot;</span><span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span></pre></p>
<p class="first_para">现在让我们写一个可以将<code>Times (Value &quot;n&quot;, Plus (Value &quot;x&quot;, Value &quot;y&quot;))</code>输出为类似<code>n * (x + y)</code>的东西的函数。实际上，我要写两个函数，一个用于将表达式转换成漂亮的字符串，另一个将其打印出来（这样做的原因是我可能也想将同样的字符串写入到一个文件，而我又不想为了这点小事就将整个函数再重写一遍——尽可能复用代码）。</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">rec</span> to_string e =
  <span style="color: #06c; font-weight: bold;">match</span> e <span style="color: #06c; font-weight: bold;">with</span>
    Plus <span style="color: #6c6;">&#40;</span>left, right<span style="color: #6c6;">&#41;</span>   -&gt; <span style="color: #3cb371;">&quot;(&quot;</span> ^ <span style="color: #6c6;">&#40;</span>to_string left<span style="color: #6c6;">&#41;</span> ^ <span style="color: #3cb371;">&quot; + &quot;</span> ^ <span style="color: #6c6;">&#40;</span>to_string right<span style="color: #6c6;">&#41;</span> ^ <span style="color: #3cb371;">&quot;)&quot;</span>
  | Minus <span style="color: #6c6;">&#40;</span>left, right<span style="color: #6c6;">&#41;</span>  -&gt; <span style="color: #3cb371;">&quot;(&quot;</span> ^ <span style="color: #6c6;">&#40;</span>to_string left<span style="color: #6c6;">&#41;</span> ^ <span style="color: #3cb371;">&quot; - &quot;</span> ^ <span style="color: #6c6;">&#40;</span>to_string right<span style="color: #6c6;">&#41;</span> ^ <span style="color: #3cb371;">&quot;)&quot;</span>
&nbsp;
  | Times <span style="color: #6c6;">&#40;</span>left, right<span style="color: #6c6;">&#41;</span>  -&gt; <span style="color: #3cb371;">&quot;(&quot;</span> ^ <span style="color: #6c6;">&#40;</span>to_string left<span style="color: #6c6;">&#41;</span> ^ <span style="color: #3cb371;">&quot; * &quot;</span> ^ <span style="color: #6c6;">&#40;</span>to_string right<span style="color: #6c6;">&#41;</span> ^ <span style="color: #3cb371;">&quot;)&quot;</span>
  | Divide <span style="color: #6c6;">&#40;</span>left, right<span style="color: #6c6;">&#41;</span> -&gt; <span style="color: #3cb371;">&quot;(&quot;</span> ^ <span style="color: #6c6;">&#40;</span>to_string left<span style="color: #6c6;">&#41;</span> ^ <span style="color: #3cb371;">&quot; / &quot;</span> ^ <span style="color: #6c6;">&#40;</span>to_string right<span style="color: #6c6;">&#41;</span> ^ <span style="color: #3cb371;">&quot;)&quot;</span>
&nbsp;
  | Value v -&gt; v
  ;;
&nbsp;
<span style="color: #06c; font-weight: bold;">let</span> print_expr e =
  <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALprint_endline"><span style="">print_endline</span></a> <span style="color: #6c6;">&#40;</span>to_string e<span style="color: #6c6;">&#41;</span>;;</pre></p>
<p class="first_para">（注意：<code>^</code>操作符用于联结字符串。）</p>
<p>立刻对其进行测试：</p>
<p><pre class="ocaml"># print_expr <span style="color: #6c6;">&#40;</span>Times <span style="color: #6c6;">&#40;</span>Value <span style="color: #3cb371;">&quot;n&quot;</span>, Plus <span style="color: #6c6;">&#40;</span>Value <span style="color: #3cb371;">&quot;x&quot;</span>, Value <span style="color: #3cb371;">&quot;y&quot;</span><span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span>;;
<span style="color: #6c6;">&#40;</span>n * <span style="color: #6c6;">&#40;</span>x + y<span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span></pre></p>
<p class="first_para">模式匹配的一般形式是：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">match</span> object <span style="color: #06c; font-weight: bold;">with</span>
  pattern    -&gt;  result
| pattern    -&gt;  result
    ...</pre></p>
<p class="first_para">左边的模式可以是简单的，如上面的<code>to_string</code>中所示，也可以是复杂的、嵌套的。下面一个例子是分解形式为<code>n * (x + y)</code>或者<code>(x + y) * n</code>的表达式的函数，为此我们将用到一个嵌套模式：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">rec</span> multiply_out e =
  <span style="color: #06c; font-weight: bold;">match</span> e <span style="color: #06c; font-weight: bold;">with</span>
    Times <span style="color: #6c6;">&#40;</span>e1, Plus <span style="color: #6c6;">&#40;</span>e2, e3<span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span> -&gt;
      Plus <span style="color: #6c6;">&#40;</span>Times <span style="color: #6c6;">&#40;</span>multiply_out e1, multiply_out e2<span style="color: #6c6;">&#41;</span>,
            Times <span style="color: #6c6;">&#40;</span>multiply_out e1, multiply_out e3<span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span>
  | Times <span style="color: #6c6;">&#40;</span>Plus <span style="color: #6c6;">&#40;</span>e1, e2<span style="color: #6c6;">&#41;</span>, e3<span style="color: #6c6;">&#41;</span> -&gt;
      Plus <span style="color: #6c6;">&#40;</span>Times <span style="color: #6c6;">&#40;</span>multiply_out e1, multiply_out e3<span style="color: #6c6;">&#41;</span>,
            Times <span style="color: #6c6;">&#40;</span>multiply_out e2, multiply_out e3<span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span>
  | Plus <span style="color: #6c6;">&#40;</span>left, right<span style="color: #6c6;">&#41;</span> -&gt; Plus <span style="color: #6c6;">&#40;</span>multiply_out left, multiply_out right<span style="color: #6c6;">&#41;</span>
  | Minus <span style="color: #6c6;">&#40;</span>left, right<span style="color: #6c6;">&#41;</span> -&gt; Minus <span style="color: #6c6;">&#40;</span>multiply_out left, multiply_out right<span style="color: #6c6;">&#41;</span>
  | Times <span style="color: #6c6;">&#40;</span>left, right<span style="color: #6c6;">&#41;</span> -&gt; Times <span style="color: #6c6;">&#40;</span>multiply_out left, multiply_out right<span style="color: #6c6;">&#41;</span>
  | Divide <span style="color: #6c6;">&#40;</span>left, right<span style="color: #6c6;">&#41;</span> -&gt; Divide <span style="color: #6c6;">&#40;</span>multiply_out left, multiply_out right<span style="color: #6c6;">&#41;</span>
  | Value v -&gt; Value v
  ;;</pre></p>
<p class="first_para">下面是结果：</p>
<p><pre class="ocaml"># print_expr <span style="color: #6c6;">&#40;</span>multiply_out <span style="color: #6c6;">&#40;</span>Times <span style="color: #6c6;">&#40;</span>Value <span style="color: #3cb371;">&quot;n&quot;</span>, Plus <span style="color: #6c6;">&#40;</span>Value <span style="color: #3cb371;">&quot;x&quot;</span>, Value <span style="color: #3cb371;">&quot;y&quot;</span><span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span>;;
<span style="color: #6c6;">&#40;</span><span style="color: #6c6;">&#40;</span>n * x<span style="color: #6c6;">&#41;</span> + <span style="color: #6c6;">&#40;</span>n * y<span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span></pre></p>
<p class="first_para"><code>multiply_out</code>函数是如何运作的呢？第一个模式是匹配形如<code>e1 * (e2 + e3)</code>的表达式的<code>Times (e1, Plus (e2, e3))</code>。现在看一下这个模式的右边的东西，其实它就等同于<code>(e1 * e2) + (e1 * e3)</code>。</p>
<p>第二个模式的工作基本类似，除了针对形如<code>(e1 + e2) * e3</code>的表达式。</p>
<p>剩下的模式并不会改变表达式的形式，但是它们也十分关键，它们递归对子表达式调用了<code>multiply_out</code>函数。这确保了表达式中的所有的子表达式都能得到处理（除非你只需要分解表达式的最顶层，如果这样，你只需要将这些余下的模式替换成简单的<code>e -&gt; e</code>规则）。</p>
<p>我们是否能逆向进行（即提取公共的子表达式）？当然可以（不过要复杂一些）！下面的版本只针对顶层表达式。你一定可以对其进行扩展来完美地处理表达式的所有层次或者更加复杂的情况：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> factorize e =
  <span style="color: #06c; font-weight: bold;">match</span> e <span style="color: #06c; font-weight: bold;">with</span>
    Plus <span style="color: #6c6;">&#40;</span>Times <span style="color: #6c6;">&#40;</span>e1, e2<span style="color: #6c6;">&#41;</span>, Times <span style="color: #6c6;">&#40;</span>e3, e4<span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span> <span style="color: #06c; font-weight: bold;">when</span> e1 = e3 -&gt; Times <span style="color: #6c6;">&#40;</span>e1, Plus <span style="color: #6c6;">&#40;</span>e2, e4<span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span>
  | Plus <span style="color: #6c6;">&#40;</span>Times <span style="color: #6c6;">&#40;</span>e1, e2<span style="color: #6c6;">&#41;</span>, Times <span style="color: #6c6;">&#40;</span>e3, e4<span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span> <span style="color: #06c; font-weight: bold;">when</span> e2 = e4 -&gt; Times <span style="color: #6c6;">&#40;</span>Plus <span style="color: #6c6;">&#40;</span>e1, e3<span style="color: #6c6;">&#41;</span>, e4<span style="color: #6c6;">&#41;</span>
  | e -&gt; e
  ;;</pre></p>
<p><pre class="ocaml"># factorize <span style="color: #6c6;">&#40;</span>Plus <span style="color: #6c6;">&#40;</span>Times <span style="color: #6c6;">&#40;</span>Value <span style="color: #3cb371;">&quot;n&quot;</span>, Value <span style="color: #3cb371;">&quot;x&quot;</span><span style="color: #6c6;">&#41;</span>, Times <span style="color: #6c6;">&#40;</span>Value <span style="color: #3cb371;">&quot;n&quot;</span>, Value <span style="color: #3cb371;">&quot;y&quot;</span><span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span>;;
- : expr = Times <span style="color: #6c6;">&#40;</span>Value <span style="color: #3cb371;">&quot;n&quot;</span>, Plus <span style="color: #6c6;">&#40;</span>Value <span style="color: #3cb371;">&quot;x&quot;</span>, Value <span style="color: #3cb371;">&quot;y&quot;</span><span style="color: #6c6;">&#41;</span><span style="color: #6c6;">&#41;</span></pre></p>
<p class="first_para">上面的<code>factorize</code>函数引入了另外两个特点。你可以对每个模式匹配添加所谓的<strong>守卫</strong>（guard）。一个守卫（条件）是指跟在<code>when</code>的条件表达式，它表示该模式匹配只有在模式被匹配了<em>并且</em>满足了在<code>when</code>子句中的条件时，才会发生模式匹配。</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">match</span> object <span style="color: #06c; font-weight: bold;">with</span>
  pattern    <span style="color: #6c6;">&#91;</span> <span style="color: #06c; font-weight: bold;">when</span> condition <span style="color: #6c6;">&#93;</span>   -&gt;  result
  pattern    <span style="color: #6c6;">&#91;</span> <span style="color: #06c; font-weight: bold;">when</span> condition <span style="color: #6c6;">&#93;</span>   -&gt;  result
    ...</pre></p>
<p class="first_para">第二个特点是用于测试两个表达式之间“结构相等”（structural equality）的<code>=</code>操作符。这表示会递归进入每个表达式检测它们是否在每一个级别上都完全一致。</p>
<p>OCaml可以在编译期检测出你是否已经在你的模式中将所有的可能性都涉及了。如果我给上面的<code>type expr</code>类型定义添加一个<code>Product</code>变体的话：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">type</span> expr = Plus <span style="color: #06c; font-weight: bold;">of</span> expr * expr        <span style="color: #5d478b; font-style: italic;">(* 表示a + b *)</span>
          | Minus <span style="color: #06c; font-weight: bold;">of</span> expr * expr       <span style="color: #5d478b; font-style: italic;">(* 表示a - b *)</span>
          | Times <span style="color: #06c; font-weight: bold;">of</span> expr * expr       <span style="color: #5d478b; font-style: italic;">(* 表示 a * b *)</span>
          | Divide <span style="color: #06c; font-weight: bold;">of</span> expr * expr      <span style="color: #5d478b; font-style: italic;">(* 表示 a / b *)</span>
          | Product <span style="color: #06c; font-weight: bold;">of</span> expr list       <span style="color: #5d478b; font-style: italic;">(* 表示 a * b * c * ... *)</span>
          | Value <span style="color: #06c; font-weight: bold;">of</span> string            <span style="color: #5d478b; font-style: italic;">(* &quot;x&quot;, &quot;y&quot;, &quot;n&quot;, etc. *)</span>
	  ;;</pre></p>
<p class="first_para">然后我未对<code>to_string</code>函数加以修改就重新编译它，结果OCaml报告了以下警告：</p>
<pre>
Warning: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
Product _
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.nirvanastudio.org/ocaml/data-types-and-matching.html/feed</wfw:commentRss>
		</item>
		<item>
		<title>OCaml基础知识</title>
		<link>http://www.nirvanastudio.org/ocaml/the-basics-of-ocaml.html</link>
		<comments>http://www.nirvanastudio.org/ocaml/the-basics-of-ocaml.html#comments</comments>
		<pubDate>Sat, 09 Sep 2006 15:10:33 +0000</pubDate>
		<dc:creator>ShiningRay</dc:creator>
		
		<category><![CDATA[OCaml]]></category>

		<guid isPermaLink="false">http://www.nirvanastudio.org/ocaml/the-basics-of-ocaml.html</guid>
		<description><![CDATA[原文地址：http://www.ocaml-tutorial.org/the_basics 翻译：ShiningRay
注释
OCaml的注释是用(* and *)来分隔的，如下：
(* 这是一个单行注释 *)
&#160;
(* 这是一个
 * 多行
 * 注释
 *)
换句话说，注释的方式和原始的C(/* ... */)一样。
目前还没有单行注释的语法（就是类似Perl的# ...或者C99/C++/Java的// ...）。是否使用##...还没有确定，而且我极力推荐OCaml的人以后能将其加入到语言中。
OCaml可以处理嵌套的(* ... *)，这可以让你很方便地注释某个代码区域：
(* 这段代码坏的……
&#160;
(* 质数测试. *)
let is_prime n =
  (* 对自己说：在邮件列表上问一下 *) XXX;;
&#160;
*&#41;
函数调用
假设你已经写了一个函数——叫它repeated吧——，它需要一个字符串s和一个数字n作为参数，并返回一个新的字符串，包含了s重复了n次的结果。
在大部分C派生的语言中，调用这个函数类似于：
repeated &#40;&#34;hello&#34;, 3&#41;  /* C代码 */
这表示“使用两个参数调用函数repeated，第一个参数是字符串hello，第二个参数是数字3”。
OCaml，和其他函数式语言一样，在函数调用的写法和括号的用法是有所不同的，所以容易产生很多错误。在OCaml中同样的函数调用是：
repeated &#34;hello&#34; 3  (* OCaml代码 *)
注意——不需要括号，参数之间也不需要逗号。
那么，repeated ("hello", 3)在OCaml中则有另外一番深刻的含义。它表示“使用一个参数调用函数repeated，该参数为包含两个元素的一个‘pair’（偶对）结构”。这当然是错误的，因为repeated函数需要两个参数，而非一个，同时在任何情况下第一个参数都应该是一个字符串，而非一个偶对。不过目前还不用管偶对（元组“tuple”）只要记住在函数调用的参数两边加上括号和中间加上逗号是错误的。
再看另外一个函数——get_string_from_user——它输入一个提示字符串并返回由用户输入的字符串。我们希望将这个字符串传入repeated。下面是C和OCaml的版本：
/* C代码： */
repeated &#40;get_string_from_user &#40;&#34;请输入一个字符串。&#34;&#41;, 3&#41;
(* OCaml代码： *)
repeated &#40;get_string_from_user &#34;请输入一个字符串。&#34;&#41; 3
仔细看一下括号和逗号的用法。一般规则是：“括号要放在整个函数调用两边——不要将括号放在函数调用的参数周围”。下面还有一些例子：
f 5 &#40;g [...]]]></description>
			<content:encoded><![CDATA[<p>原文地址：<a href="http://www.ocaml-tutorial.org/the_basics">http://www.ocaml-tutorial.org/the_basics</a> 翻译：ShiningRay</p>
<h2><a name="OCaml_Comments" id="OCaml_Comments">注释</a></h2>
<p class="first_para">OCaml的注释是用<code>(*</code> and <code>*)</code>来分隔的，如下：</p>
<p><pre class="ocaml"><span style="color: #5d478b; font-style: italic;">(* 这是一个单行注释 *)</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">(* 这是一个
 * 多行
 * 注释
 *)</span></pre></p>
<p class="first_para">换句话说，注释的方式和原始的C(<code>/* ... */</code>)一样。</p>
<p>目前还没有单行注释的语法（就是类似Perl的<code># ...</code>或者C99/C++/Java的<code>// ...</code>）。是否使用<code>##...</code>还没有确定，而且我极力推荐OCaml的人以后能将其加入到语言中。</p>
<p>OCaml可以处理嵌套的<code>(* ... *)</code>，这可以让你很方便地注释某个代码区域：</p>
<p><pre class="ocaml"><span style="color: #5d478b; font-style: italic;">(* 这段代码坏的……
&nbsp;
(* 质数测试. *)</span>
<span style="color: #06c; font-weight: bold;">let</span> is_prime n =
  <span style="color: #5d478b; font-style: italic;">(* 对自己说：在邮件列表上问一下 *)</span> XXX;;
&nbsp;
*<span style="color: #6c6;">&#41;</span></pre></p>
<h2><a name="Calling_functions">函数调用</a></h2>
<p class="first_para">假设你已经写了一个函数——叫它<code>repeated</code>吧——，它需要一个字符串<code>s</code>和一个数字<code>n</code>作为参数，并返回一个新的字符串，包含了<code>s</code>重复了<code>n</code>次的结果。</p>
<p>在大部分C派生的语言中，调用这个函数类似于：</p>
<p><pre class="c">repeated <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;hello&quot;</span>, <span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#41;</span>  <span style="color: #808080; font-style: italic;">/* C代码 */</span></pre></p>
<p class="first_para">这表示“使用两个参数调用函数<code>repeated</code>，第一个参数是字符串hello，第二个参数是数字3”。</p>
<p>OCaml，和其他函数式语言一样，在函数调用的写法和括号的用法是有所不同的，所以容易产生很多错误。在OCaml中同样的函数调用是：</p>
<p><pre class="ocaml">repeated <span style="color: #3cb371;">&quot;hello&quot;</span> <span style="color: #c6c;">3</span>  <span style="color: #5d478b; font-style: italic;">(* OCaml代码 *)</span></pre></p>
<p class="first_para">注意——<strong>不需要</strong>括号，参数之间也<strong>不需要</strong>逗号。</p>
<p>那么，<code>repeated ("hello", 3)</code>在OCaml中则有另外一番深刻的含义。它表示“使用<strong>一个</strong>参数调用函数<code>repeated</code>，该参数为包含两个元素的一个‘pair’（偶对）结构”。这当然是错误的，因为<code>repeated</code>函数需要两个参数，而非一个，同时在任何情况下第一个参数都应该是一个字符串，而非一个偶对。不过目前还不用管偶对（元组“tuple”）只要记住在函数调用的参数两边加上括号和中间加上逗号是错误的。</p>
<p>再看另外一个函数——<code>get_string_from_user</code>——它输入一个提示字符串并返回由用户输入的字符串。我们希望将这个字符串传入<code>repeated</code>。下面是C和OCaml的版本：</p>
<p><pre class="c"><span style="color: #808080; font-style: italic;">/* C代码： */</span>
repeated <span style="color: #66cc66;">&#40;</span>get_string_from_user <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;请输入一个字符串。&quot;</span><span style="color: #66cc66;">&#41;</span>, <span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#41;</span></pre></p>
<p><pre class="ocaml"><span style="color: #5d478b; font-style: italic;">(* OCaml代码： *)</span>
repeated <span style="color: #6c6;">&#40;</span>get_string_from_user <span style="color: #3cb371;">&quot;请输入一个字符串。&quot;</span><span style="color: #6c6;">&#41;</span> <span style="color: #c6c;">3</span></pre></p>
<p class="first_para">仔细看一下括号和逗号的用法。一般规则是：“括号要放在整个函数调用两边——不要将括号放在函数调用的参数周围”。下面还有一些例子：</p>
<p><pre class="ocaml">f <span style="color: #c6c;">5</span> <span style="color: #6c6;">&#40;</span>g <span style="color: #3cb371;">&quot;hello&quot;</span><span style="color: #6c6;">&#41;</span> <span style="color: #c6c;">3</span>    <span style="color: #5d478b; font-style: italic;">(* f有三个参数，g有一个参数 *)</span>
f <span style="color: #6c6;">&#40;</span>g <span style="color: #c6c;">3</span> <span style="color: #c6c;">4</span><span style="color: #6c6;">&#41;</span>            <span style="color: #5d478b; font-style: italic;">(* f有一个参数，g有两个参数 *)</span>
&nbsp;
# repeated <span style="color: #6c6;">&#40;</span><span style="color: #3cb371;">&quot;hello&quot;</span>, <span style="color: #c6c;">3</span><span style="color: #6c6;">&#41;</span>;;     <span style="color: #5d478b; font-style: italic;">(* OCaml 将会指出这个错误 *)</span>
This expression has <span style="color: #06c; font-weight: bold;">type</span> string * int but is here used <span style="color: #06c; font-weight: bold;">with</span> <span style="color: #06c; font-weight: bold;">type</span> string</pre></p>
<h2><a name="Defining_a_function" id="Defining_a_function">定义一个函数</a></h2>
<p class="first_para">你已经知道如果在其他主流语言中如何定义函数（对熟悉Java的来说，静态方法）。那么在OCaml要怎么做呢？</p>
<p>OCaml的语法十分简练，令人感觉愉悦。下面是一个输入两个浮点数并计算平均数的函数：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> average a b =
  <span style="color: #6c6;">&#40;</span>a +. <span style="color: #060;">b</span><span style="color: #6c6;">&#41;</span> /. <span style="color: #c6c;">2.0</span>;;</pre></p>
<p class="first_para">将这段内容输入OCaml“顶层”（在Unix上，从外壳中输入<code>ocaml</code>），然后就应该看到如下内容：</p>
<p><pre class="ocaml"># <span style="color: #06c; font-weight: bold;">let</span> average a b =
  <span style="color: #6c6;">&#40;</span>a +. <span style="color: #060;">b</span><span style="color: #6c6;">&#41;</span> /. <span style="color: #c6c;">2.0</span>;;
<span style="color: #06c; font-weight: bold;">val</span> average : <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALfloat"><span style="">float</span></a> -&gt; <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALfloat"><span style="">float</span></a> -&gt; <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALfloat"><span style="">float</span></a> = &lt;fun&gt;</pre></p>
<p class="first_para">如果你仔细看函数定义，然后看看OCaml给你输出的内容，你就会产生一系列疑问：</p>
<ul>
<li>代码中额外的句号是干什么用的？</li>
<li><code>float -&gt; float -&gt; float</code>这串东西是什么意思？</li>
</ul>
<p class="first_para">在下一节中，我会来回答这些问题，不过首先我要继续在C中定义同样的函数（Java中的定义应该会和C十分相似），而且这也很可能会引发更多的疑问。下面是<code>average</code>的C版本：</p>
<p><pre class="c"><span style="color: #993333;">double</span>
average <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">double</span> a, <span style="color: #993333;">double</span> b<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
  <span style="color: #b1b100;">return</span> <span style="color: #66cc66;">&#40;</span>a + b<span style="color: #66cc66;">&#41;</span> / <span style="color: #cc66cc;">2</span>;
<span style="color: #66cc66;">&#125;</span></pre></p>
<p class="first_para">现在再回头看一下简短得多的OCaml定义。你很有可能会问：</p>
<ul>
<li>为什么在OCaml的版本中并没有定义<code>a</code>和<code>b</code>的类型？OCaml是如何知道它们是何种类型的（更进一步问，OCaml<em>是否</em>知道它们的类型，或者OCaml完全就是动态类型的）？</li>
<li>在C中，<code>2</code>会隐式转换成一个<code>double</code>，但是为何OCaml不能做同样的事情？</li>
<li>OCaml写<code>return</code>的方式是什么？</li>
</ul>
<p class="first_para">好吧，现在就来回答其中一些问题。</p>
<ul>
<li>OCaml是一个静态强类型语言（换句话说，类型上没有任何像Perl中出现的那种动态的东西）。</li>
<li>OCaml使用<em>类型推断</em>来计算出类型，所以无需进行声明。如果像上面那样在OCaml顶层输入代码，OCaml会告诉你（它所认为的）你的函数的正确类型。</li>
<li>OCaml不会进行任何隐含转换。如果要一个浮点数，必须写作<code>2.0</code>，因为<code>2</code>是一个整数。</li>
<li>因为OCaml不允许操作符重载，所以用不同的操作符来表示“两个整数相加”（<code>+</code>）和“两个浮点数相加”（<code>+.</code>注意后面的点），其他算术操作符也类似。</li>
<li>OCaml会返回函数中最后一个表达式，所以无需像C那样写<code>return</code>。</li>
</ul>
<p class="first_para">真正的细节在下面。</p>
<p><a name="Basic_types"></a><br />
<h2>基本类型</h2>
<p class="first_para">OCaml中的基本类型有：</p>
<pre>OCaml 类型     范围

int            32位处理器上是31位有符号整数（大约在+/- 10亿之间），
               或者在64位处理器上是63位有符号整数
float          IEEE 双精度浮点数，等同于C的double
bool           一个布尔型，true或false
char           一个8位字符
string         一个字符串
unit           写作 ()
</pre>
<p class="first_para">OCaml内部保留了一个<code>int</code>中的一位是为了能自动进行内存使用的管理（垃圾收集）。这就是为什么基本的<code>int</code>是31位而非32位（所以，如果使用64位平台，<code>int</code>是63位）。实际上除了一些特殊的场合，这并不成为一个问题。例如，如果你是对循环进行计数，OCaml会限制数到10亿而非20亿。这也不会成为一个问题，因为如果在任何语言中，要使用到接近这个上限的数字，你就应该使用大数字bignum（OCaml中的<code>Nat</code>和<code>Big_int</code>模块）。不过，如果你确实需要32位类型来处理一些事情的话（eg.写加密代码或者网络栈相关的），OCaml还提供了一个<code>nativeint</code>类型，匹配了你的平台上本地的整型。</p>
<p>OCaml没有基本的无符号整数类型，但是你可以使用<code>nativeint</code>来达到相同的效果。目前我只能说OCaml完全没有单精度浮点数的支持。</p>
<p>OCaml提供了一个用于字符的<code>char</code>类型，例如，写作<code>'x'</code>。不幸的是<code>char</code>类型并不能支持Unicode或者UTF-8。这在OCaml中是一个很严重的瑕疵，应该被修正，但是现在可以使用<a href="http://camomile.sourceforge.net/" class="external" title="http://camomile.sourceforge.net/">comprehensive Unicode libraries</a>来解决这个问题。</p>
<p>字符串不仅仅是字符的列表。它们有自己更加有效的内部表示方式。</p>
<p><code>unit</code>类型是一种类似于C中<code>void</code>的东西，but we&#8217;ll talk about it more below.</p>
<p><a name="Implicit_vs__explicit_casts"></a><br />
<h2><span>隐式转换对比显式转换</span></h2>
<p class="first_para">在C派生的语言中int在某些特定的环境下会自动提升为浮点数。例如，如果写<code>1 + 2.5</code>，那么第一个参数（是一个整数）会提升为一个浮点数，结果也同样是一个浮点数。就好像你写了<code>((double) 1) + 2.5</code>，不过都是隐含完成的。</p>
<p>OCaml则从不像这样进行隐式转换。在OCaml中，<code>1 + 2.5</code>则是一个类型错误。OCaml中的<code>+</code>操作符要求两个整数作为参数，而这里我们给出了一个整数和一个浮点数，所以它会报告这样的错误：</p>
<pre># 1 + 2.5;;
      ^^^
This expression has type float but is here used with type int
</pre>
<p>要将两个浮点数相加，你则需要另外一个不同的操作符，<code>+.</code>（注意后面的点）。</p>
<p>OCaml不会自动将整数提升为浮点数，所以这也是一个错误：</p>
<pre># 1 +. 2.5;;
  ^
This expression has type int but is here used with type float
</pre>
<p class="first_para">这里OCaml在抗议第一个参数。</p>
<p>如果你确实需要将一个整数和一个浮点数相加，要怎么做？（假设它们存储在叫做<code>i</code>和<code>f</code>）。在OCaml中你需要显式转换：</p>
<p><pre class="ocaml"><a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALfloat_of_int"><span style="">float_of_int</span></a> i +. <span style="color: #060;">f</span>;;</pre></p>
<p class="first_para"><code>float_of_int</code>是一个输入了一个<code>int</code>并返回一个<code>float</code>。除此之外还有很多此类函数，名字诸如<code>int_of_float</code>、<code>char_of_int</code>、<code>int_of_char</code>、<code>string_of_int</code>等等，同时功能基本和名字吻合。</p>
<p>由于将<code>int</code>转换为<code>float</code>是一个特别常用的操作，<code>float_of_int</code>函数有一个较短的别名：以上例子可以简单地写为：</p>
<p><pre class="ocaml"><a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALfloat"><span style="">float</span></a> i +. <span style="color: #060;">f</span>;;</pre></p>
<p class="first_para">（注意和C不一样，一个类型和一个函数有同样的名称在OCaml中这是完全有效的。）</p>
<h3>隐式转换好，还是显式转换好?</h3>
<p class="first_para">你可能会想这些显式转换很丑陋，甚至很耗费时间，。首先，OCaml需要显式转换才能进行类型推断（见下文），同时类型推断又是一个奇妙的、节省时间的特点，可以很方便地抵消显式转换所带来的额外的键盘输入，如果你以前花了很长时间来调试C程序的话，你就会知道(a)隐式的类型转换所造成的错误很难被发现，(b)你常常会花很多时间来计算在哪里要发生隐式转换。让类型转换明确化就可以帮助进行调试。第三，某些转换（尤其是 int &lt;-&gt; float）实际上是十分昂贵的操作，所以你应该自己来做而不是隐藏。</p>
<p><a name="Ordinary_functions_and_recursive_functions">#</a><br />
<h2><span>普通的函数和递归函数</span></h2>
<p class="first_para">和C派生的语言不同，除非你明确使用<code>let rec</code>替代<code>let</code>来声明一个函数，否则这个函数就不能是递归的。下面是一个递归函数的例子：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">rec</span> range a b =
  <span style="color: #06c; font-weight: bold;">if</span> a &gt; b <span style="color: #06c; font-weight: bold;">then</span> <span style="color: #6c6;">&#91;</span><span style="color: #6c6;">&#93;</span>
  <span style="color: #06c; font-weight: bold;">else</span> a :: range <span style="color: #6c6;">&#40;</span>a<span style="color: #c6c;">+1</span><span style="color: #6c6;">&#41;</span> b
  ;;</pre></p>
<p class="first_para">注意<code>range</code>调用了其自身。</p>
<p><code>let</code> 和 <code>let rec</code>之间唯一的区别就在于函数名的范围。如果上面的函数仅仅是用<code>let</code>来定义的话，当调用<code>range</code>时就会尝试调用一个已经存在的（前面定义过的）叫做<code>range</code>的函数，而不是当前被定义的函数。使用<code>let</code>和使用<code>let rec</code>定义的函数之间没有任何性能上的差别，所以如果你愿意，你可以总是使用<code>let rec</code>形式来进行定义，就可以获得类似于C语言的语义。</p>
<p><a name="Types_of_functions"></a><br />
<h2><span>函数的类型</span></h2>
<p class="first_para">因为类型推断的存在，你可能很少甚至从不需要明确写出函数的类型。不过，OCaml常常会输出它所认为的函数的类型，所以你需要知道它的语法。对于一个带有参数<code>arg<sub>1</sub></code>和<code>arg<sub>2</sub></code>、……的函数，编译器会输出：</p>
<pre>f : arg1 -&gt; arg2 -&gt; ... -&gt; argn -&gt; rettype
</pre>
<p class="first_para">箭头语法现在看起来很奇怪，不过之后当我们接触所谓的“currying”，你就会明白为何要选它。现在我就要给出几个例子。</p>
<p>我的函数<code>repeated</code>输入一个字符串和一个整数并返回一个字符串的类型为：</p>
<pre>repeated : string -&gt; int -&gt; string
</pre>
<p class="first_para">我们的函数<code>average</code>输入两个浮点数并返回一个浮点数的，类型为：</p>
<pre>average : float -&gt; float -&gt; float
</pre>
<p class="first_para">OCaml标准的<code>int_of_char</code>类型转换函数：</p>
<pre>int_of_char : char -&gt; int
</pre>
<p class="first_para">如果一个函数什么也不返回（对C和Java程序员来说应该是<code>void</code>），那么我们写为返回<code>unit</code>类型。例如，下面是OCaml中等同于<code>fputc</code>的是：</p>
<pre>output_char : out_channel -&gt; char -&gt; unit
</pre>
<h3>多态函数</h3>
<p class="first_para">现在对于某些东西有些奇怪。如何才能使一个函数可以输入<em>任何类型</em>作为其参数呢？下面是一个输入一个参数的奇怪函数，但是忽略了这个参数，仅返回3：</p>
<p><pre class="ocaml"><span style="color: #06c; font-weight: bold;">let</span> give_me_a_three x = <span style="color: #c6c;">3</span>;;</pre></p>
<p class="first_para">那么这个函数的类型是什么呢？在OCaml中我们使用一个特殊的占位符来表示“任何你能想到的类型”。这是一个单引号跟着一个字母。前面的函数的类型一般会写作：</p>
<pre>give_me_a_three : 'a -&gt; int
</pre>
<p class="first_para">其中<code>'a</code>实际上就是表示任何类型。例如，你可以这样调用： <code>give_me_a_three "foo"</code>或者<code>give_me_a_three 2.0</code>，两者在OCaml中都是有效的表达式。</p>
<p>多态函数到底能有什么用现在你可能还不清楚，不过它们确实十分有用也十分常见，所以我们将稍后讨论它们。（提示：多态时一种类似于C++或Java 1.5中的模版和泛型的东西）。</p>
<p><a name="Type_inference"></a><br />
<h2><span>类型推断</span></h2>
<p class="first_para">那么本教程的主题是函数式变成有很多<strong>十分神奇的特点</strong>，同时OCaml则是包含了所有这些神奇特点的一门语言，这就使其对于真正的程序员的使用来说是一们非常实用的语言。但是奇怪的是这些大部分神奇的特点和“函数式编程”都毫无关系。实际上，我已经讲述了第一个神奇特点，而且我还未讲解为何函数式变成要叫做“函数式”的。不管怎样，下面是第一个神奇特点：类型推断。</p>
<p>只要记住：你不需要声明你的函数和变量的类型，因为OCaml会为你计算出来</p>
<p>另外OCaml会继续检查所有的类型匹配（甚至在不同的文件之间）。</p>
<p>但是OCaml也是一个实用的语言，因此它在类型系统中包含了一些后门可以让你在特殊的必要场合中绕过它。一般只有大牛们可能会绕过类型检验。</p>
<p>让我们回到前面我们输入到OCaml顶层的函数<code>average</code>：</p>
<p><pre class="ocaml"># <span style="color: #06c; font-weight: bold;">let</span> average a b =
  <span style="color: #6c6;">&#40;</span>a +. <span style="color: #060;">b</span><span style="color: #6c6;">&#41;</span> /. <span style="color: #c6c;">2.0</span>;;
<span style="color: #06c; font-weight: bold;">val</span> average : <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALfloat"><span style="">float</span></a> -&gt; <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALfloat"><span style="">float</span></a> -&gt; <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALfloat"><span style="">float</span></a> = &lt;fun&gt;</pre></p>
<p class="first_para">说来奇怪！OCaml能自己计算出该函数输入两个<code>float</code>参数并输出一个<code>float</code>。</p>
<p>它是如何做到的呢？首先它看在哪里用到了<code>a</code>和<code>b</code>，即在表达式<code>(a +. b)</code>中。现在，<code>+.</code>则是一个总是输入两个<code>float</code>参数，所以通过简单的探测，<code>a</code>和<code>b</code>一定都是<code>float</code>类型的。</p>
<p>第二，<code>/.</code>函数返回一个<code>float</code>，同时它也是<code>average</code>的返回值，所以，<code>average</code>必然返回一个<code>float</code>。最后结果就是<code>average</code>会拥有以下类型签名：</p>
<pre>average : float -&gt; float -&gt; float
</pre>
<p class="first_para">类型推断明显对于这类短小的程序很方便，不过甚至对于大型程序，都很有效，同时它是个重要的省时特点，因为它可以避免其他语言中的一大类错误，如段错误（segfault）、的<code>NullPointerException</code>和<code>ClassCastException</code>（或者是一些重要的但常常被忽略的运行时警告，如Perl）。</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nirvanastudio.org/ocaml/the-basics-of-ocaml.html/feed</wfw:commentRss>
		</item>
		<item>
		<title>JavaScript高级程序设计</title>
		<link>http://www.nirvanastudio.org/javascript/professional-javascript-for-web-developers.html</link>
		<comments>http://www.nirvanastudio.org/javascript/professional-javascript-for-web-developers.html#comments</comments>
		<pubDate>Fri, 08 Sep 2006 15:14:45 +0000</pubDate>
		<dc:creator>ShiningRay</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[书籍]]></category>

		<guid isPermaLink="false">http://www.nirvanastudio.org/news/professional-javascript-for-web-developers.html</guid>
		<description><![CDATA[
基本信息

【英文名】Professional JavaScript for Web Developers
【作者】Nicholas C. Zakas
【译者】曹力 张欣
【ISBN】7115152098
【出版时间】2006-9-15 
【页码】670
【原出版社】Wrox
【简介】本书从最早期Netscape浏览器中的Javascript开始讲起，直到当前它对XML和Web服务的具体支持，展示了如何充分利用这种功能强大的语言开发自己的应用程序，以解决当今Web开发者面对的商业问题。
活动主页

译者序
]]></description>
			<content:encoded><![CDATA[<p><a class="imagelink" href="http://www.nirvanastudio.org/wp-content/uploads/2006/09/profession-javascript-cover.jpg" title="profession-javascript-cover.jpg"><img id="image112"  style="float:right" src="http://www.nirvanastudio.org/wp-content/uploads/2006/09/profession-javascript-cover.thumbnail.jpg" alt="profession-javascript-cover.jpg" /></a></p>
<h3>基本信息</h3>
<ul>
<li>【英文名】<a href="http://www.wrox.com/WileyCDA/WroxTitle/productCd-0764579088.html">Professional JavaScript for Web Developers</a></li>
<li>【作者】Nicholas C. Zakas</li>
<li>【译者】<a href="http://wiki.nirvanastudio.org/wiki/ShiningRay">曹力</a> 张欣</li>
<li>【ISBN】7115152098</li>
<li>【出版时间】2006-9-15 </li>
<li>【页码】670</li>
<li>【原出版社】<a href="http://www.wrox.com/">Wrox</a></li>
<li>【简介】本书从最早期Netscape浏览器中的Javascript开始讲起，直到当前它对XML和Web服务的具体支持，展示了如何充分利用这种功能强大的语言开发自己的应用程序，以解决当今Web开发者面对的商业问题。</li>
<li><a href="http://www.dearbook.com.cn/2006/jsppk97/index.htm">活动主页</a></li>
</ul>
<h3>译者序</h3>
<p> <a href="http://www.nirvanastudio.org/javascript/professional-javascript-for-web-developers.html#more-111" class="more-link">(more&#8230;)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.nirvanastudio.org/javascript/professional-javascript-for-web-developers.html/feed</wfw:commentRss>
		</item>
	</channel>
</rss>
