Julia
using Test
"""
返回一个闭包
"""
#> "返回一个闭包\n"
function ClosureFactory(x)
# 此处不能写成匿名函数的形式,因为匿名函数没有默认参数
closure(f=nothing) = isnothing(f) ? x : f(x) # return a closure
end
#> ClosureFactory (generic function with 1 method)
methods(ClosureFactory(-2))
#> # 2 methods:
#> [1] (::var"#closure#11")() in Main at none:6
#> [2] (::var"#closure#11")(f) in Main at none:6
@testset "Closure factory working tests" begin
@test ClosureFactory(-2)() == -2
@test ClosureFactory(-2)(abs) == 2
@test ClosureFactory(-2)(sqrt ∘ abs) == √2
end
#> Test Summary: | Pass Total
#> Closure factory working tests | 3 3
#> Test.DefaultTestSet("Closure factory working tests", Any[], 3, false, false)
# 10 data closures
zero, one, two, three, four, five, six, seven, eight, nine = map(ClosureFactory, 0:9)
#> 10-element Vector{var"#closure#11"{Int64}}:
#> (::var"#closure#11"{Int64}) (generic function with 2 methods)
#> (::var"#closure#11"{Int64}) (generic function with 2 methods)
#> (::var"#closure#11"{Int64}) (generic function with 2 methods)
#> (::var"#closure#11"{Int64}) (generic function with 2 methods)
#> (::var"#closure#11"{Int64}) (generic function with 2 methods)
#> (::var"#closure#11"{Int64}) (generic function with 2 methods)
#> (::var"#closure#11"{Int64}) (generic function with 2 methods)
#> (::var"#closure#11"{Int64}) (generic function with 2 methods)
#> (::var"#closure#11"{Int64}) (generic function with 2 methods)
#> (::var"#closure#11"{Int64}) (generic function with 2 methods)
# 4 operator closure factories
plus(k) = x -> x + k
#> plus (generic function with 1 method)
#> minus (generic function with 1 method)
#> times (generic function with 1 method)
dividedBy(k) = x -> x / k
#> dividedBy (generic function with 1 method)
@testset "Fuctional Programming tests" begin
@test eight(minus(three())) == 5
@test seven(times(five())) == 35
end
#> Test Summary: | Pass Total
#> Fuctional Programming tests | 2 2
#> Test.DefaultTestSet("Fuctional Programming tests", Any[], 2, false, false)
JavaScript
const closureFactory = x => (f => f === undefined ? x : f(x));
const [zero, one, two, three, four, five, six, seven, eight, nine] =
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(closureFactory);
const plus = k => (x => x + k);
const minus = k => (x => x - k);
const times = k => (x => x * k);
const dividedBy = k => (x => (x - x % k) / k);
console.log(eight(minus(three())));
console.log(seven(times(five())));
#> 5
#> 35