---
title: "Functional Programming in Ruby（一）"
author: "jonathan_zz"
date: "2008-10-30T13:30:08Z"
tags: ["FP", "LISP", "Ruby", "编程", "脚本"]
slug: "functional-programming-in-ruby"
draft: false
lastmod: "2008-10-30T13:30:08Z"
id: 260022
url: "https://jonathan-zz.iteye.com/blog/260022"
---

接触Ruby也有一年多了，没有写过多少代码，只写过一些小的脚本。7月份的时候买了《The Ruby programming language》，打算系统的学习Ruby。虽然已经看过不少的ruby代码，但是看到6.8节“Functional Programming”的时候还是有种眼前一亮的感觉。恩，来看看函数像对象一样在代码间轻盈跃动的感觉吧：

```
# This module defines methods and operators for FP
module Functional

  def apply(enum)
     eunm.map &self
  end
  alias | apply

  def reduce(enum)
     enum.inject &self
  end
  alias <= reduce
end
```

然后将这个模块加入到Proc和Method类中：

```
class Proc; include Functional; end
class Method; include Functional; end
```

现在我们可以这样写代码：

```
sum = lambda {|x, y| x+y}
mean = (sum<=a)/a.size
deviation = lambda {|x| x-mean}
square = lambda {|x| x*x}
standardDeviation = Math.sqrt((sum<=square)|(deviation|a))/(a.size-1)
```

其实在使用map或者inject这类迭代器操纵block的时候，就已经是在用函数式风格编程，只是上面的magic使得整个的编程过程看起来更lisp一些。呵呵，这只是我自己的拙见，还有太多的东西要学习。

未完待续……