# How do I create a function from an expression

**URL:** https://discourse.julialang.org/t/how-do-i-create-a-function-from-an-expression/12349
**Category:** General Usage
**Tags:** question
**Created:** [July 13, 2018, 4:38am UTC](https://discourse.julialang.org/t/how-do-i-create-a-function-from-an-expression/12349 "2018-07-13T04:38:40Z")
**Posts on this page:** 1
**Showing post:** 21

<div class="post-metadata">

### Author: ![chakravala](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chakravala/32/6832_2.png) [@chakravala](https://discourse.julialang.org/u/chakravala)
#### Post date: [July 13, 2018, 4:46pm UTC](https://discourse.julialang.org/t/how-do-i-create-a-function-from-an-expression/12349/21 "2018-07-13T16:46:32Z")

</div>

Actually, I have just figured out to do this macro without `Base.invokelatest` and updated `SyntaxTree` :

```nohighlight
julia> using SyntaxTree, BenchmarkTools

julia> g = genfun(:(-(cos(x))),[:x])
(::#3) (generic function with 1 method)

julia> @btime $g(1.0)
  40.790 ns (0 allocations: 0 bytes)
-0.5403023058681398

julia> f = @genfun -cos(x) [x]
(::#3) (generic function with 1 method)

julia> @btime $f(1.0)
  40.801 ns (0 allocations: 0 bytes)
-0.5403023058681398

```

Now the evaluation is much faster because it is not using `Base.invokelatest` anymore. The implementation

```nohighlight
macro genfun(expr,args)
    :($(Expr(:tuple,args.args...))->$expr)
end

genfun(expr,args) = :(@genfun $expr [$(args...)]) |> eval

```

is very simple to write in Julia in the end, it is now part of the [SyntaxTree](https://github.com/chakravala/SyntaxTree.jl) package.

---

_[View the full topic](https://discourse.julialang.org/t/how-do-i-create-a-function-from-an-expression/12349)._
