Skip to main content

🌏 梦开始的地方

题目

用你找到的三门语言(注意,某语言的方言和该语言算作同一种语言)写出下文 Scheme 语言的等价代码:

(define (make-withdraw balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"v我50,撫慰我支離破碎的心")))

(define W1 (make-withdraw 100))
(define W2 (make-withdraw 100))

(W1 50)
; 50
(W2 70)
; 30
(W1 20)
; 30

附加题:

  • 20%:在用法不变的前提下,用你用过的其中一种语言或者 Lisp 及其方言增加以下功能:

    (v50 W1)

    使得余额增加 50 元。

说明

这道题会让人不由自主的写一个类出来当伪函数,然而出题人的本意是使用闭包,因此问题关键点在于如何捕获。

题解

下面给出四种语言的解

C++

#include <iostream>
#include <functional>

std::function<void(int)> withdraw(int balance) {
return [balance] (int amount) mutable {
if (balance >= amount) {
balance -= amount;
if (amount >= 0)
std::cout << balance << std::endl;
} else {
std::cout << "v我50,撫慰我支離破碎的心" << std::endl;
}
};
}

void v50(std::function<void(int)>& w) {
w(-50);
}


int main() {
auto w1 = withdraw(100), w2 = withdraw(100);
w1(50);
w2(70);
w2(50);
v50(w2);
w2(50);
}

Python

我提交的版本:

def withdraw(balance):
def apply(amount, balance = [balance]):
if balance[0] >= amount:
balance[0] -= amount
if amount >= 0:
print(balance[0])
else:
print('v我50,撫慰我支離破碎的心')
return apply


def v50(w):
w(-50)


w1 = withdraw(100)
w2 = withdraw(100)
w1(50)
w2(70)
w2(50)
v50(w2)
w2(50)

更好的版本:

def withdraw(balance):
def apply(amount):
nonlocal balance
if balance >= amount:
balance -= amount
if amount >= 0:
print(balance)
else:
print('v我50,撫慰我支離破碎的心')
return apply


def v50(w):
w(-50)


w1 = withdraw(100)
w2 = withdraw(100)
w1(50)
w2(70)
w2(50)
v50(w2)
w2(50)

JavaScript

function withdraw(balance) {
return function(amount) {
if (balance >= amount) {
balance -= amount
if (amount >= 0) console.log(balance)
} else {
console.log('v我50,撫慰我支離破碎的心')
}
}
}

function v50(w) {
w(-50)
}

var w1 = withdraw(100)
var w2 = withdraw(100)
w1(50)
w2(70)
w2(50)
v50(w2)
w2(50)

Kotlin

fun withdraw(balance: Int): (Int)->Unit {
var balance = balance
return { amount: Int->
if (balance >= amount) {
balance -= amount
if (amount >= 0)
println(balance)
} else {
println("v我50,撫慰我支離破碎的心")
}
}
}

fun v50(w: (Int)->Unit) = w(-50)


fun main() {
val w1 = withdraw(100)
val w2 = withdraw(100)
w1(50)
w2(70)
w2(50)
v50(w2)
w2(50)
}