美文网首页
Nested Functions

Nested Functions

作者: christ_yang | 来源:发表于2020-05-30 23:03 被阅读0次

(嵌套函数)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表达式内早于函数定义的绑定。

编程风格

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

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

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

相关文章

网友评论

      本文标题:Nested Functions

      本文链接:https://www.haomeiwen.com/subject/weqhzhtx.html