Nested Functions

(嵌套函数)Nested Functions

根据let表达式:let b1 b2 … bn in e end的使用规则,我们在其中定义任意绑定,包括function绑定,这是一种好的编程风格。

实例

fun count (from : int, to : int) = 
  if from = to
  then to :: []
  else from :: cout(from+1, to)
fun countup_from0(x : int) = 
  count(1, x)

我们不想对外暴露辅助函数、或困扰别人时,我们就需要使用let以实现嵌套函数

fun countup_from1 (x : int) =
  let fun count (from : int, to : int) =
    if from = to
    then to :: []
    else from :: count(from+1,to)
  in
    count (1,x)
  end

更好的版本:
fun countup_from1_better (x : int) =
  let fun count (from : int) =
    if from = x
    then x :: []
    else from :: count(from+1)
  in
    count 1
  end

通过上面的例子,我们可以知道,嵌套函数可以使用其外层环境已定义的绑定,如:参数、在let表达式内早于函数定义的绑定。

编程风格

在函数内部定义辅助函数是一种良好的编程风格,如果辅助函数:

  • 辅助函数在其他地方不太可能会使用到
  • 在其他地方可能会被滥用
  • 以后可能被更改或删除

代码设计中的一个基本权衡:重用代码可以节约时间和精力,并且可以避免一些错误,但是同时它也会导致重用的代码在以后难以更改。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。