---
title: "高阶函数的威力"
author: "诺铁"
date: "2011-06-27T19:06:21Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-06-28T01:39:03Z"
id: 1106898
url: "https://notyy.iteye.com/blog/1106898"
---

#### 高阶函数的威力

 

从[All about monads](http://www.google.com.hk/search?rlz=1C1GPCK_enCN427CN427&sourceid=chrome&ie=UTF-8&q=All%20about%20monads)里看到的解释mondad的例子，令人感动的优雅代码，我用纯foldl改写，去除了其中monad的内容，这样初学haskell的人应该也看得懂。

我们先定义类型羊(Sheep)和两个函数，求羊的父亲和母亲

```
type Sheep = String

father :: Sheep -> Sheep
father s = "f_" ++ s

mother :: Sheep -> Sheep
mother m = "m_" ++ m
```

如果要查找羊的奶奶或者爷爷怎么办呢？很简单

```
grandma :: Sheep -> Sheep
grandma s = mother (mother s)

grandpa :: Sheep -> Sheep
grandpa s = father (father s)
```

当然，依次类推，你可以写上几页代码把羊的十八代祖宗都写出来，但我相信正常的程序员不会愿意那么干的。

那么我们就来看看利用高阶函数能写出怎样优雅的实现。

```
--  我们传递一个函数(Sheep->Sheep)的集合来作为第二个参数，然后利用foldl来计算它。
findAncestor :: Sheep -> [(Sheep -> Sheep)] -> Sheep
findAncestor s l = foldl getParent s l  -- 将函数作为参数传递
        where getParent s f = f s
```

用法

```
findAncestor "dolly" [mother,father,father]   -- dolly's mother's father's father
findAncestor "dolly" [father,mother,father,mother]   -- dolly's father's
```