# Assign variables automatically to a function

Lets consider that I've this function:

fn = a*x^2 + b*x + c;


The idea here is to assign automatically the variables a, b, c and x to a function so it becomes something like that:

fn[x_,a_,b_,c_] := a*x^2 + b*x + c


In order to do this I've tried to extract the varibles from fn using Variables:

Sort@Variables@fn


{a, b, c, x}

Then in order to apply it to the function fn I do the following:

fn1@Variables@fn /. List -> Sequence


fn1[a, b, c, x]

Questions:

• Is it possible to add the Blanks to the former expression in order to have fn1[a_,b_,c_,x_]?

One of my fail attempt to do this was to use Blank@#&/@Sort@Variables@fn but it's obviously not working.

• One other point is that if you consider that you've found a way to automaticly have fn1[a_,b_,c_,x_], how to assign the value of fn to fn1[a_,b_,c_,x_] without having the fn1[a_,b_,c_,x_] is protected message?
-
I don't think that going this way is a good idea. It is possible to do technically, but I don't see how you can make this semantically robust. Either you do it fully automatically, but then you don't know neither the number of resulting variables nore their ordering. Or you have some manual step, but then it makes sense to just simply define the function the way you want it, from the start. –  Leonid Shifrin May 29 '13 at 10:45
mhm, if there is no way to do it automatically and robust it would be as you say easier to define the function with its variables directly. I just wondered if there was a lazy way to assign variables without typing them. –  Öskå May 29 '13 at 10:50
I think the same effect wil be obtained with this type of function definition: Function[{x1,x2...},body]. And will be definitely simpler. –  Kuba May 29 '13 at 11:15
This is strongly related (perhaps even a duplicate) mathematica.stackexchange.com/questions/10067/… –  Ajasja May 29 '13 at 20:24

The following works:

fn = a*x^2 + b*x + c;
Clear[fn1];
autofunc[fn_] :=
ToString[
fn1[
ToExpression /@
Apply[StringJoin,
With[{var = ToString /@ Sort@Variables@fn},
Transpose@Append[{var}, Table["_", {Length@var}]]], 2] /.
List -> Sequence]] <> ":= " <> ToString[fn, InputForm]

autofunc[fn]
ToExpression@autofunc[fn]
fn1[1, 2, 3, 4]


"fn1[a_, b_, c_, x_]:= c + b*x + a*x^2"

27

(I didn't say it was pretty..)

You have to evaluate it to see the number of variables in the new function (which is displayed as a "string"). Also Clear[fn1] is important in this case. With a bit more playing around I'm sure I could work out a way to automate the naming of the new function.

To some who might find that answer useful I would recommend to use {var = ToString /@ Sort@DeleteDuplicates@Cases[fn, _Symbol, Infinity]} instead of {var = ToString /@ Sort@Variables@fn} so it works with every functions (& not only polynomials). –  Öskå Jun 3 '13 at 15:13