This just looks at first glance to all be a little unnecessary. Julia 
supports anonymous functions just fine, so if this isn't in a 
performance-critical loop (where the proposed `feval` approach will be 
slow, too) I'd recommend something more like that.

julia> f = (x)->3x-2x+5
(anonymous function)

julia> g = (x)->4x-3x/2
(anonymous function)

julia> g(f(3))
20.0

julia> 3 |> f |> g
20.0

julia> foldl(|>, [3 f g])
20.0

julia> feval(funs, x) = foldl(|>, {x; funs...})
feval (generic function with 2 methods)

julia> feval([f g], 3)
20.0

No global state was harmed by the execution of this method.
On Wednesday, December 18, 2013 7:19:43 AM UTC-6, Dominik Holenstein wrote:
>
> I am new to Julia programming and not an expert either. 
>
> While working on a project which involves the translation of Matlab code 
> to Julia I had the idea to write a
>  feval(f, x1=NaN)
>
> function in Julia to evaluate a single expression or an array of two or 
> more expressions by using just one function. 
>
>
> This is the code of the feval(f, x1=NaN) function:
>
> function feval(f,x1 = NaN)
>    if isnan(x1) == false
>       global x = x1
>    end
>    if typeof(f) == Array{Expr,1}
>       n = size(f,1)
>       F = zeros(n,1)
>       for i=1:n
>          F[i] = eval(f[i])
>       end
>    elseif typeof(f) == Expr
>       F = 0
>       F = eval(f)
>    else
>       println("f is a ", typeof(f))
>       error("f is nor an expression nor a single array of expressions.")
>    end
>    return F
> end
>
>
> You can use this function with a single expression or with an array of 
> expressions (x = 3.5) : 
>
> julia> f1 = :(3*x - 2*x + 5)
> :(+(-(*(3,x),*(2,x)),5))
>
> julia> f2 = :(4*x - 3*x/2)
> :(-(*(4,x),/(*(3,x),2)))
>
> julia> f = [f1;f2]
> 2-element Array{Expr,1}:
> :(+(-(*(3,x),*(2,x)),5))
> :(-(*(4,x),/(*(3,x),2)))
>
> julia> x = 3.5
> 3.5
>
>
> The results:
> julia> res_f1 = feval(f1)
> 8.5
>
> julia> res_f2 = feval(f2)
> 8.75
>
>
> julia> res_f = feval(f)
> 2x1 Array{Float64,2}:
> 8.5
> 8.75
>
>
> Further, you can deliver an optional input value for x with the function 
> call:
>
> julia> res_f1 = feval(f1, 5.25)
> 10.25
>
>
> Note that this changes the global variable x:
> julia> x
> 5.25
>
>
>
> In general: Is this appraoch a good or bad idea? Or are there better 
> options to consider (types, macros etc.)?
>
> Many thanks for your support.
>
> Regards,
> Dominik
>

Reply via email to