Fernet
Fernet

Reputation: 183

Defining a function from an expression stored in a var

I asked a similar question yesterday but it seemed I had to change my approach, so I did, but now I'm sort of stuck again.

Anyway, what I want to do is something along the line of

(def bar '(* 2 %))
(#(bar) 2) ;this line doesn't work.
(#(* 2 %) 2) ;this is what I want the line that doesn't work to do.

Thing is, I want the expression stored in a var so I could do something like

(def bar2 (list (first bar) 3 (nth bar 2)))
(#(bar2) 2) ;this line obviously doesn't work either.

Maybe there's another approach than the # anonymous function reader macro.

I'm doing a project in genetic programming for uni so what I need to do is have an expression that I can change and make into a function.

Upvotes: 2

Views: 85

Answers (2)

mobyte
mobyte

Reputation: 3752

(def bar '(* 2 %))

((eval (read-string (str "#" bar))) 3)
=> 6

If you used named parameter(s) in expression it would look cleaner:

(def bar '(* 2 p))

(def f-expr (concat '(fn [p]) [bar]))

((eval f-expr) 3)
=> 6

Upvotes: 2

JohnJ
JohnJ

Reputation: 4833

If you want to evaluate quoted expressions at run time (as opposed to compile time, à la macros), you can just use eval:

(eval '(* 10 12))
;=> 120

(def arg 12)
(def bar '(* 10 arg))
(eval bar)
;=> 120

Normally one steers clear of eval (macros will perform better, for one thing), but it might be what you want for playing with genetic algorithms.

Upvotes: 1

Related Questions