From 184668ca6ef273f4d60b646e0a23f1afe36fca28 Mon Sep 17 00:00:00 2001 From: Alexander Plavin Date: Sun, 21 Jul 2024 20:45:55 -0400 Subject: [PATCH] support more functions in constructorof Now works with regular functions and non-closure anonymous functions as well. --- src/functions.jl | 2 ++ test/runtests.jl | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/functions.jl b/src/functions.jl index 739aacd..ee8d39d 100644 --- a/src/functions.jl +++ b/src/functions.jl @@ -6,6 +6,8 @@ struct FunctionConstructor{F} end _isgensym(s::Symbol) = occursin("#", string(s)) @generated function (fc::FunctionConstructor{F})(args...) where F + isempty(args) && return Expr(:new, F) + T = getfield(parentmodule(F), nameof(F)) # We assume all gensym names are anonymous functions _isgensym(nameof(F)) || return :($T(args...)) diff --git a/test/runtests.jl b/test/runtests.jl index 9ef66c7..f4e68ff 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -246,7 +246,7 @@ end end end -@testset "Anonymous function constructors" begin +@testset "default function constructors" begin function multiplyer(a, b) x -> x * a * b end @@ -259,6 +259,10 @@ end multbc = @inferred constructorof(typeof(mult23))("b", "c") @inferred multbc("a") @test multbc("a") == "abc" + + @test (@inferred constructorof(typeof(sin))()) === sin + f = x -> x^2 + @test (@inferred constructorof(typeof(f))()) === f end struct Adder{V} <: Function