---
title: "函数式语言嵌套调用"
author: "joinhack"
date: "2011-01-02T18:03:00Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-01-02T18:03:00Z"
id: 857679
url: "https://joinhack.iteye.com/blog/857679"
---

看看以下的嵌套调用

def searchFrom(i: Int): Int =

if (i &gt;= args.length) -1// 不要越过最后一个参数

else if (args(i).startsWith("-")) searchFrom(i + 1)// 跳过选项

else if (args(i).endsWith(".scala")) i // 找到!

else searchFrom(i + 1) // 继续找

val i = searchFrom(0)

 

这个方法里面使用嵌套函数调用，如果是传统的指令式语言，我会奉劝不要使用嵌套调用，因为在足够深的嵌套调用后，一定出现栈溢出，你回想下c++中树的遍历就是使用queue这些数据结构来避免嵌套调用帮助实现遍历算法的，而函数式语言解救了这一切，让嵌套调用成为主要的思考方式，并且不会出现栈溢出，这也使得可读性大大加强。