# Macro design recommendations for \`do-end\` like semantics

**URL:** <https://discourse.julialang.org/t/macro-design-recommendations-for-do-end-like-semantics/103610>\
**Category:** General Usage\
**Tags:** macros\
**Created:** [September 7, 2023, 1:38pm UTC](https://discourse.julialang.org/t/macro-design-recommendations-for-do-end-like-semantics/103610 "2023-09-07T13:38:14Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![kdheepak](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kdheepak/32/10881_2.png) [@kdheepak](https://discourse.julialang.org/u/kdheepak)\
**Post date:** [September 7, 2023, 1:38pm UTC](https://discourse.julialang.org/t/macro-design-recommendations-for-do-end-like-semantics/103610/1 "2023-09-07T13:38:14Z")

</div>

In Julia, there’s a function `do` block syntax like so:

```julia
foo() do x
  println(x)
end

```

where `foo` is defined like `foo(f::Function)`

I’m interested in writing a macro that affects a block. i.e. I want user facing code to look something like this:

```julia
foo() do x
  println(x)
end

```

but where `foo` is defined like this instead: `foo(expr::Expr)`

I’ve tried writing a macro but this following example doesn’t work (because `@foo()` is evaluated first):

```julia
julia> @foo() function(x)
  println(x)
end

ERROR: syntax: extra token "function" after end of expression
Stacktrace:
 [1] top-level scope
   @ none:1

```

And this would work but it is easy for users to accidentally remove the space between `@foo` and `()` and that leads to the previous structure which throws an error.

```julia
@foo () function(x)
  println(x)
end

```

I’m curious if anyone has suggestions for alternative designs here?

---

<div class="post-metadata">

**Author:** ![mcabbott](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mcabbott/32/6603_2.png) [@mcabbott](https://discourse.julialang.org/u/mcabbott)\
**Post date:** [September 7, 2023, 1:48pm UTC](https://discourse.julialang.org/t/macro-design-recommendations-for-do-end-like-semantics/103610/2 "2023-09-07T13:48:15Z")

</div>

It’s not so clear to me what you want, but macros can certainly take `do` blocks:

```julia
julia> macro foo(exs...)
         @show exs; nothing
       end;

julia> @foo(y, 2, z=3) do x
         g(x)
       end
exs = (:((x,)->begin
          #= REPL[138]:2 =#
          g(x)
      end), :y, 2, :(z = 3))

```

---

<div class="post-metadata">

**Author:** ![kdheepak](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kdheepak/32/10881_2.png) [@kdheepak](https://discourse.julialang.org/u/kdheepak)\
**Post date:** [September 7, 2023, 2:17pm UTC](https://discourse.julialang.org/t/macro-design-recommendations-for-do-end-like-semantics/103610/3 "2023-09-07T14:17:16Z")

</div>

Ah nice! I thought I tried this but must have messed up the number of arguments and failed to see the dispatch error. That helps! Thanks!!
