# Problem with function as an argument

I want to write a function like the following:

s[u_, v_, x_, val_] := u[val]/NIntegrate[u'[x] v[x] + u'[x] v'[x], {x, 0, 1}]


So I can evaluate something like

s[Cos[x], Sin[3 x], x, 5]


I have a strong feeling that my approach is incorrect, however, I couldn't find the right one.

Update:

Thanks to b.gatessucks, who wrote the correct version of what I was trying to achieve. However, after that I tried to use that approach on lists:

r = {1, 2, 3, 4, 5};
u[x_, i_] := Sin[r[[i]] x];
A = Table[s[u[#, i] &, u[#, j] &, 5], {i, 5}, {j, 5}]


After this, I get a matrix, but I also get a bunch of errors, so I don't know if I can trust the output. The errors are:

Part::pspec: Part specification #2 is neither an integer nor a list of integers.
Part::pspec: Part specification #2 is neither an integer nor a list of integers.
Part::pspec: Part specification #2 is neither an integer nor a list of integers.
General::stop: "Further output of Part::pspec: will be suppressed during this calculation."

-
You have an extra _ in the right-hand side. Next, you can drop the x argument and evaluate you function as s[Cos[#] &, Sin[3 #] &, 5]. –  b.gatessucks Nov 22 '12 at 8:48
It actually worked, thanks! However, would be nice to find some guide on operators as such, google is not very helpful with those symbols. –  prazuber Nov 22 '12 at 8:59
"some guide on operators" - see this, for starters... –  J. M. is back. Nov 22 '12 at 9:00
and this thread full of useful resources. –  b.gatessucks Nov 22 '12 at 9:02

Despite some practice with Mathematica, I still consider myself a newbie. However, I have come to understand that a function and an expression are two different things, despite the fact that the documentation seems to use them indistinctly (if I am wrong, glad to hear the comment of an expert!)

So, what I did and that seems to work with s is to consider u and v as expression parameters - therefore the use of /. inside, with the symbol parameter x - and define the functions inside, so as to apply ' later on. The code is:

s[u_, v_, x_, val_] := Module[{f, g},
f[t_] := u /. x -> t;
g[t_] := v /. x -> t;
f[val]/NIntegrate[f'[t] g[t] + f'[t] g'[t], {t, 0, 1}]
];


which gives the output

In[9]:= s[Cos[x], Sin[3 x], x, 5]

Out[9]= 2.36249

Hope helps.

(By the way: I believe it is in these cases that you want to use HoldFirst, HoldAll and related evaluation attributes.)

-
Thank you, this is exactly what I needed! –  prazuber Nov 29 '12 at 6:47