关于闭包与函数式编程的一点总结

在B站看到一个CS50教学视频
有一节提到 Lisp 语言,所以想看看它的不同之处

在一篇教程中看到 Lisp 的特点是有一个举例:假设你想写一个函数,输入一个数 n ,返回把 n 与传入参数 (argument)相加的函数

; Lisp
(defun addn (n)
    #'(lambda (x)
        (+ x n)))

这里使用到了闭包的特性;

js 中也有类似的特性,使用 js 也可以实现上诉的功能;

// 闭包 使用示例 index.js
function addN(n) {
    return function (x) { return x + n }
}

var funcy = addN(10)
console.log(funcy(6))

var res = addN(10)(6)
console.log(res)
// > node index.js

在网络上又查询了一些资料,又学到了使用js实现闭包的案例;

似乎与函数式编程也有了联系;

// https://www.cnblogs.com/wenbinjiang/p/13476342.html
function Lexical_Closure_Demo() {
    var a = 0
    function increase() {
        a++
    }

    function getValue() {
        return a
    }
    return {
        increase,
        getValue
    }
}
var demo = Lexical_Closure_Demo()
demo.increase()
demo.increase()
console.log(demo.getValue())
demo.increase()
demo.increase()
demo.increase(); demo.increase()
console.log(demo.getValue())

在函数式编程中,函数不仅可以当作返回值,也可以作为入参,又想起了当年使用js实现回调的写法了

// Return a function that approximates the derivative of f
// using an interval of dx, which should be appropriately small.
function derivative(f, dx) {
    return function (x) {
        return (f(x + dx) - f(x)) / dx;
    };
}

function func1(n) { return 2 * n }

var func2 = derivative(func1, 32)
var res = func2(5667)
console.log(res)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值