Julia Community 🟣

gfr1337
gfr1337

Posted on

Man/Boy test and why Julia doesn't specialize functional arguments by default.

module ManBoy
export man, boy, manboy
export @main

function man(k::Int, f1::Function, f2::Function, f3::Function, f4::Function, f5::Function)::Int
    x = Ref(k)
    b = () -> begin
        x[] -= 1
        man(x[], b, f1, f2, f3, f4)::Int
    end
    if x[] <= 0
        return f4() + f5()
    else
        return b()
    end
end

function boy(k::Int, f1::F1, f2::F2, f3::F3, f4::F4, f5::F5)::Int where {F1 <: Function, F2 <: Function, F3 <: Function, F4 <: Function, F5 <: Function}
    x = Ref(k)
    b = () -> begin
        x[] -= 1
        boy(x[], b, f1, f2, f3, f4)::Int
    end
    if x[] <= 0
        return f4() + f5()
    else
        return b()
    end
end

function manboy(n::Int)
    println("man($n)")
    @time println(man(n, () -> 1, () -> -1, () -> -1, () -> 1, () -> 0))
    println("boy($n)")
    @time println(boy(n, () -> 1, () -> -1, () -> -1, () -> 1, () -> 0))
end

function @main()(args)
    manboy(5)
    manboy(10)
    manboy(15)
end

end # module ManBoy

Enter fullscreen mode Exit fullscreen mode
man(5)
0
  0.095508 seconds (58.51 k allocations: 3.080 MiB, 99.78% compilation time)
boy(5)
0
  0.070338 seconds (52.65 k allocations: 2.727 MiB, 99.63% compilation time)
man(10)
-67
  0.116278 seconds (52.27 k allocations: 3.307 MiB, 27.42% gc time, 71.93% compilation time)
boy(10)
-67
  1.764479 seconds (57.47 k allocations: 3.571 MiB, 99.95% compilation time)
man(15)
-3250
  0.438978 seconds (220.55 k allocations: 163.185 MiB, 67.07% gc time, 19.28% compilation time)
boy(15)
-3250
 46.606029 seconds (261.17 k allocations: 167.955 MiB, 0.22% gc time, 99.65% compilation time)

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
oheil profile image
oheil

If you have questions or want to discuss your code it's better to try on discourse. But even there it's best to formulate some questions in words and sentences. Posting only code and output is not the best approach.