# Higher order function as macro

**URL:** <https://discourse.julialang.org/t/higher-order-function-as-macro/87867>\
**Category:** General Usage\
**Tags:** macros, metaprogramming, macro-hygiene\
**Created:** [September 27, 2022, 10:54am UTC](https://discourse.julialang.org/t/higher-order-function-as-macro/87867 "2022-09-27T10:54:41Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jlbosse](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jlbosse/32/11274_2.png) [@jlbosse](https://discourse.julialang.org/u/jlbosse)\
**Post date:** [September 27, 2022, 10:54am UTC](https://discourse.julialang.org/t/higher-order-function-as-macro/87867/1 "2022-09-27T10:54:41Z")

</div>

I am trying provide a macro form of a higher order function, but the automatic macro hygiene  
means that the name of the resulting function gets mangled.

Here is my attempt so far:

```julia
# The higher order function I want to provide the macro for
function printinput(f)
    function out(x)
         @show x
         return f(x)
    end
    return out
end

# My attempt at the macro
macro printing(ex)
    def = splitdef(ex)
    name = def[:name]
    internal_name = gensym()
    def[:name] = internal_name
    out = quote
        $(combinedef(def))
        $name = printinput($internal_name)
    end    
    return out
end

# and how I would want to use it 
@printing function f(x)
    return sin(x)
end

# should expand to
quote
    function var"#690###334"(var"#692#x")
        return Main.sin(var"#692#x")
    end
    f = Main.printinput(var"#690###334")
end

# but instead expands to 
quote
    function var"#690###334"(var"#692#x")
        return Main.sin(var"#692#x")
    end
    var"#691#f" = Main.printinput(var"#690###334")
end

```

how do I prevent the function name `f` to get mangled?

---

<div class="post-metadata">

**Author:** ![jlbosse](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jlbosse/32/11274_2.png) [@jlbosse](https://discourse.julialang.org/u/jlbosse)\
**Post date:** [September 27, 2022, 11:07am UTC](https://discourse.julialang.org/t/higher-order-function-as-macro/87867/2 "2022-09-27T11:07:37Z")

</div>

Nvm, I found the solution: Use `esc(name)` to prevent mangling.

So do

```julia
macro printing(ex)
    def = splitdef(ex)
    name = def[:name]
    internal_name = gensym()
    def[:name] = internal_name
    out = quote
        $(combinedef(def))
        $(esc(name)) = printinput($internal_name)
    end    
    return out
end

```

for the macro
