# first steps to metaprogramming

**URL:** <https://discourse.julialang.org/t/first-steps-to-metaprogramming/17715>\
**Category:** New to Julia\
**Created:** [November 19, 2018, 1:40pm UTC](https://discourse.julialang.org/t/first-steps-to-metaprogramming/17715 "2018-11-19T13:40:04Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [November 19, 2018, 2:01pm UTC](https://discourse.julialang.org/t/first-steps-to-metaprogramming/17715/3 "2018-11-19T14:01:11Z")

</div>

The first thing you should ask yourself when writing metaprogramming is “why do I need metaprogramming for this”. In this example, the function:

```julia
function wp_loop(x, n::Int)
    v = 1.0
    for i in 1:n 
        v *= (x-i)
    end
    return v
end

```

or perhaps

```julia
function wp_prod(x, n::Int)
    prod(i -> x-i, 1:n)
end

```

evaluates the polynomial without metaprogramming. If you really need to specialize on `n` you can do

```julia
function wp_val(x, ::Val{n}) where {n}
    v = 1.0
    for i in 1:n 
        v *= (x-i)
    end
    return v
end

```

and get the specialized:

```julia
julia> @code_llvm wp_vaö(4.0, Val(3))
  %1 = fadd double %0, -1.000000e+00
  %2 = fadd double %0, -2.000000e+00
  %3 = fmul double %1, %2
  %4 = fadd double %0, -3.000000e+00
  %5 = fmul double %3, %4
  ret double %5
}

```

If this is just a learning exercise and you want to create a function based on an expression, you could do:

```julia
julia> @eval function fp_4(x)
           $(wp(4))
       end
fp_4 (generic function with 1 method)

julia> fp_4(7)
360

```

---

_[View the full topic](https://discourse.julialang.org/t/first-steps-to-metaprogramming/17715)._
