I have earlier asked how to make allTrue[{x,list},test] function that protects the placeholder symbol x from evaluation in current context in the same way as Table[expr,{x,...}] protects x
The recipe that I ended up using failed intermittently, and I found the problem down to be caused by automatic conversion of lists to PackedArrays. Here's a failing example
SetAttributes[allTrue, HoldAll];
allTrue[{var_, lis_}, expr_] :=
LengthWhile[lis,
TrueQ[ReleaseHold[Hold[expr] /. HoldPattern[var] -> #]] &] ==
Length[lis];
allTrue[{y, Developer`ToPackedArray[{1, 1, 1}]}, y > 0]
I want allTrue[{x,{1,2,3}},x>0] to return True regardless of whether {1,2,3} gets automatically converted into PackedArray, what is a better way to implement it?
This is a version I've been using for quite a while (wrote it for a second edition of my book originally, but I ended up using it a lot). If arguments represent some unevaluated code, then the test function must have HoldAll or HoldFirst attributes if we want a single piece of code representing one specific clause to be passed to it in its unevaluated form (which may or may not be desirable).
ClearAll[fastOr];
Attributes[fastOr] = {HoldRest};
fastOr[test_, {args___}] := fastOr[test, args];
fastOr[test_, args___] :=
TrueQ[Scan[
Function[arg, If[test[arg], Return[True]], HoldAll],
Hold[args]]];
Edit: I just noticed that the solution by Daniel Reeves at the bottom of the page linked in the question, is very similar to this one. The main difference is that I care about both short-circuiting and keeping arguments unevaluated (see below), while Daniel focuses on the short-circuiting part only.
It does have a short-circuiting behavior. We need HoldRest attribute since we want to preserve the arguments in their unevaluated form. We also need the HoldAll (or HoldFirst) attribute in a pure function to preserve each of the arguments unevaluated until it is passed to test. Whether or not it gets evaluated before it is used in the body of test depends now on the attributes of test. As an example:
Clear[fullSquareQ];
fullSquareQ[x_Integer] := IntegerQ[Sqrt[x]];
In[13]:= Or ## Map[fullSquareQ, Range[50000]] // Timing
Out[13]= {0.594, True}
In[14]:= fastOr[fullSquareQ, Evaluate[Range[10000]]] // Timing
Out[14]= {0., True}
Here is an example where we pass as arguments some pieces of code inducing side effects (printing). The code of the last argument has no chance to execute, since the result has already been determined at the previous clause:
In[15]:= fastOr[# &, Print["*"]; False, Print["**"]; False,
Print["***"]; True, Print["****"]; False]
During evaluation of In[15]:= *
During evaluation of In[15]:= **
During evaluation of In[15]:= ***
Out[15]= True
Note that, since fastOr accepts general pieces of unevaluated code as clauses for Or, you have to wrap your list of values in Evaluate if you don't care that they are going to be evaluated at the start ( as is the case with the Range example above).
Finally, I will illustrate the programmatic construction of held code for fastOr, to show how it can be used (consider it a tiny crash course on working with held expressions if you wish). The following function is very useful when working with held expressions:
joinHeld[a___Hold] := Hold ## Replace[Hold[a], Hold[x___] :> Sequence[x], {1}];
Example:
In[26]:= joinHeld[Hold[Print[1]], Hold[Print[2], Print[3]], Hold[], Hold[Print[4]]]
Out[26]= Hold[Print[1], Print[2], Print[3], Print[4]]
Here is how we use it to construct programmatically the held arguments that were used in the example with Print-s above:
In[27]:=
held = joinHeld ## MapThread[Hold[Print[#]; #2] &,
{NestList[# <> "*" &, "*", 3], {False, False, True, False}}]
Out[27]= Hold[Print["*"]; False, Print["**"]; False, Print["***"]; True, Print["****"]; False]
To pass it to fastOr, we will use another useful idiom: append (or prepend) to Hold[args] until we get all function arguments, and then use Apply (note that, in general, if we don't want the piece we are appending / prepending to evaluate, we must wrap it in Unevaluated, so the general idiom looks like Append[Hold[parts___],Unevaluated[newpart]]):
In[28]:= fastOr ## Prepend[held, # &]
During evaluation of In[28]:= *
During evaluation of In[28]:= **
During evaluation of In[28]:= ***
Out[28]= True
Regarding the original implementation you refer to, you can look at my comment to it I made some while ago. The problem is that TakeWhile and LengthWhile have bugs for packed arrays in v. 8.0.0, they are fixed in the sources of 8.0.1 - so, starting from 8.0.1, you can use either mine or Michael's version.
HTH
Edit:
I just noticed that in the post you referred to, you wanted a different syntax. While it would not be very difficult to adopt the approach taken in fastOr to this case, here is a different implementation, which arguably is in closer correspondence with the existing language constructs for this particular syntax. I suggest to use Table and exceptions, since iterators in Table accept the same syntax as you want. Here it is:
ClearAll[AnyTrue, AllTrue];
SetAttributes[{AnyTrue, AllTrue}, HoldAll];
Module[{exany, exall},
AnyTrue[iter : {var_Symbol, lis_List}, expr_] :=
TrueQ[Catch[Table[If[TrueQ[expr], Throw[True, exany]], iter], exany]];
AllTrue[iter : {var_Symbol, lis_List}, expr_] :=
Catch[Table[If[! TrueQ[expr], Throw[False, exall]], iter], exall] =!= False;
];
A few words of explanation: I use Module on the top level since the custom exception tags we need to define just once, can as well do that at definition-time. The way to break out of Table is through exceptions. Not very elegant and induces a small performance hit, but we buy automatic dynamic localization of your iterator variables done by Table, and simplicity. To do this in a safe way, we must tag an exception with a unique tag, so we don't catch some other exception by mistake. I find using Module for creating persistent exception tags to be a very useful trick in general. Now, some examples:
In[40]:= i = 1
Out[40]= 1
In[41]:= AnyTrue[{i, {1, 2, 3, 4, 5}}, i > 3]
Out[41]= True
In[42]:= AnyTrue[{i, {1, 2, 3, 4, 5}}, i > 6]
Out[42]= False
In[43]:= AllTrue[{i, {1, 2, 3, 4, 5}}, i > 3]
Out[43]= False
In[44]:= AllTrue[{i, {1, 2, 3, 4, 5}}, i < 6]
Out[44]= True
In[45]:= AllTrue[{a, {1, 3, 5}}, AnyTrue[{b, {2, 4, 5}}, EvenQ[a + b]]]
Out[45]= True
In[46]:= AnyTrue[{a, {1, 3, 5}}, AllTrue[{b, {2, 4, 5}}, EvenQ[a + b]]]
Out[46]= False
I started with an assignment to i to show that possible global values of iterator variables don't matter - this is taken care of by Table. Finally, note that (as I commented elsewhere), your original signatures for AllTrue and AnyTrue are a bit too restrictive, in the sense that the following does not work:
In[47]:= lst = Range[5];
AllTrue[{i, lst}, i > 3]
Out[48]= AllTrue[{i, lst}, i > 3]
(since the fact that lst represents a list is not known at the pattern-matching time, due to HoldAll attribute). There is no good reason to keep this behavior, so you can just remove the _List checks: AnyTrue[iter : {var_Symbol, lis_}, expr_] and similarly for AllTrue, and this class of use cases will be covered.
Related
I have a list and I want to apply a logical test to each element, and if any one of them does not satisfy this condition, then return false. I want to write this in Mathematica or find a built-in function, but seems ForAll does not actually do that.
My question is: how to do this most efficiently?
Bonus: how about similarly for Exists function: i.e. if there is any element in the list satisfy the condition, return true.
The answer to the first portion of your question might be something along these lines:
forAll[list_, cond_] := Select[list, ! cond## &, 1] === {};
which is used like this:
forAll[{1, 2, 3, 3.5}, IntegerQ]
The "exists" function is already natively implemented as MemberQ. It could be reimplemented as:
exists[list_,cond_] := Select[list, cond, 1] =!= {};
Use it like
exists[Range#100, (10 == # &)]
which returns true as 10 is an element causing the Select to return {10} which is not equal to {}.
This answer is not intended to show the most efficient method, but rather an alternative method that serves the pedagogical purpose of showing some important core functionality in Mathematica.
nixeagle's answer avoids explicitly testing every element of the list. If the test doesn't lend itself to inclusion in the third argument of Select, then the below might be useful.
To do this, you need to learn about the standard Or and And functions, as well as the Map (/#) and Apply (##) commands which are extremely important for any Mathematica user to learn. (see this tutorial)
Here is a simple example.
In[2]:= data = RandomInteger[{0, 10}, {10}]
Out[2]= {10, 1, 0, 10, 1, 5, 2, 2, 4, 1}
In[4]:= # > 5 & /# data
Out[4]= {True, False, False, True, False, False, False, False, False, \
False}
In[6]:= And ## (# > 5 & /# data)
Out[6]= False
What is going on here is that you are mapping the function ("greater than 5") to each element of the list using Map, to get a list of True/False values. You are then applying the standard logical function And to the whole list to get the single Boolean value.
These are all very much core functionality in Mathematica and I recommend you read the documentation for these functions carefully and practice using them.
This is not the most efficient method, but for small problems you will not notice the difference.
In[11]:= Do[Select[data, ! # > 5 &, 1] === {}, {10000}] // Timing
Out[11]= {0.031, Null}
In[12]:= Do[And ## (# > 5 & /# data);, {10000}] // Timing
Out[12]= {0.11, Null}
For Exists, the alternative to Select would be MatchQ for patterns or MemberQ for explicit values. The documentation has some useful examples.
Not to be taken too seriously, but this
ClearAll[existsC];
existsC[cond_] := With[
{c = cond},
Compile[
{{l, _Integer, 1}},
Module[
{flag = False, len = Length#l},
Do[
If[cond[l[[i]]],
flag = True; Break[];
];,
{i, 1, len}];
flag
],
CompilationTarget -> "C"
]
]
appears to be around 300 times faster than nixeagle's solutions on my machine. What this does is to emit a compiled function which takes a list and compares its elements to the given condition (fixed at compile-time), returning True if any of them matches.
It is used as follows: Compile with the appropriate cond, eg
t = existsC[# == 99999 &];
and then
t[Range#100000] // timeIt
returns 2.33376*10^-6 (a worst-case scenario, as I am just searching linearly and the matching element is at the end) while
exists[Range#100000, (99999 == # &)] // timeIt
returns 0.000237162 (here, timeIt is this).
A pattern based approach:
forAll[list_, test_] := MatchQ[ list, _[__?test] ]
MemberQ already implements exists.
Mathematica 10 has a new function for this: AllTrue. When all elements pass the test my function appears to be a bit faster:
a = Range[2, 1*^7, 2];
AllTrue[a, EvenQ] // Timing // First
forAll[a, EvenQ] // Timing // First
1.014007
0.936006
However with an early exit the benefit of the new function becomes apparent:
a[[123456]] = 1;
AllTrue[a, EvenQ] // Timing // First
forAll[a, EvenQ] // Timing // First
0.031200
0.265202
Even though && and || perform short-circuit evaluation, i.e., don't evaluate their arguments unnecessarily, I suspect that solutions based on Select[] or Map[] won't benefit much from this. That's because they apply the logical test to every element, building a list of Boolean truth-values before performing the conjunction/disjunction among them. If the test you've specified is slow, it can be a real bottleneck.
So here is a variant that does short-circuit evaluation of the condition as well:
allSatisfy[list_, cond_] :=
Catch[Fold[If[cond[#2], True, Throw[False]] &, True, list]]
Testing if any element in the list satisfies the condition is nicely symmetric:
anySatisfy[list_, cond_] :=
Catch[Fold[If[cond[#2], Throw[True], False] &, False, list]]
Of course this could equally have been done (and candidly speaking, more easily) using procedural loops such as While[], but I have a soft spot for functional programming!
nixeagle got the bonus part, but the way I would've done the first part is as follows:
AllSatisfy[expr_, cond_] := Length#Select[expr, cond] == Length#expr
There's a simple solution:
In[1401]:= a = {1, 2, 3}
Out[1401]= {1, 2, 3}
In[1398]:= Boole[Thread[a[[2]] == a]]
Out[1398]= {0, 1, 0}
In[1400]:= Boole[Thread[a[[2]] >= a]]
Out[1400]= {1, 1, 0}
In[1402]:= Boole[Thread[a[[2]] != a]]
Out[1402]= {1, 0, 1}
Success!
When I use Manipulate I can do:
Manipulate[x, {u, 1, 10}]
In reality my controls are many and complicated, so I would prefer to take their
definition out of the Manipulate expression, like that:
control = {u, 1, 10}
Manipulate[x, control]
But that does result in a an error:
Manipulate argument control does not have the correct form for a \
variable specification.
Why doesn't it work that way?
Manipulate has the HoldAll attribute. You can force control to evaluate and everything works ok
control = {u, 1, 10};
Manipulate[x[u], Evaluate[control]]
The problem with this is that the variable u is not properly localised, so if you have already set, e.g., u=1 somewhere, then the Manipulate will return an error.
It might be better if you use appropriate scoping constructs such as With or DynamicModule depending on exactly what you're trying to do.
This is maybe overkill, but it ensures that u is local and moves control outside of the manipulate:
DynamicModule[{u}, With[{control = {u, 1, 10}}, Manipulate[x[u], control]]]
This
con = {u, 1, 10};
Manipulate[
u,
Evaluate#con
]
does work. I suppose it doesn't work without the Evaluate because
Attributes[Manipulate]
shows that Manipulate has the attribute HoldAll (but I may be wrong). To see the effect of this attribute, try this:
SetAttributes[f, HoldAll]
f[con]
f[Evaluate#con]
g[con]
(*
f[con]
f[{u, 1, 10}]
g[{u, 1, 10}]
*)
Thus, it appears that due to the HoldAll atribute, Manipulate simply does not see "inside" con unless you explicitly evaluate it.
I'm running a Table function which will take too much time to complete.
I wanted to know if there's a way to retrieve the results computed so far.
The proposed solution
Here is a version of Table that is Abort-able and will keep the intermediate results collected so far. It is a modified version of the solution posted here.
ClearAll[abortableTable];
SetAttributes[abortableTable, HoldAll];
abortableTable[expr_, iter__List] :=
Module[{indices, indexedRes, sowTag},
SetDelayed ##
Prepend[Thread[Map[Take[#, 1] &, List ## Hold ### Hold[iter]],
Hold], indices];
indexedRes =
If[# === {}, #, First##] &#Last#Reap[
CheckAbort[Do[Sow[{expr, indices}, sowTag], iter], {}], sowTag];
AbortProtect[
Map[First,
SplitBy[indexedRes,
Table[
With[{i = i}, Function[Slot[1][[2, i]]]],
{i, Length[Hold[iter]] - 1}]],
{-3}]]];
It should be able to take the same iterator specification as Table.
How it works
Here is how it works. The first statement (SetDelayed ##...) "parses" the iterators, assuming that they are each of the form {iteratorSymbol_,bounds__}, and assigns the list of iterator variables to the variable indices. The construction with Hold is needed to prevent possible evaluation of iterator variables. There are many ways to do this, I used just one of them. Here is how it works:
In[44]:=
{i, j, k} = {1, 2, 3};
Prepend[Thread[Map[Take[#, 1] &, List ## Hold ###
Hold[{i, 1, 10}, {j, 1, 5}, {k, 1, 3}]], Hold], indices]
Out[45]= Hold[indices, {i, j, k}]
Using SetDelayed ## the-above will then naturally produce the delayed definition of the form indices:={i,j,k}. I assigned the values to indices i,j,k to demonstrate that no unwanted evaluation of them happens when using this construct.
The next statement produces a list of collected results, where each result is grouped in a list with the list of indices used to produce it. Since indices variable is defined by delayed definition, it will evaluate every time afresh, for a new combination of indices. Another crucial feature used here is that the Do loop accepts the same iterator syntax as Table (and also dynamically localizes the iterator variables), while being a sequential (constant memory) construct. To collect the intermediate results, Reap and Sow were used. Since expr can be any piece of code, and can in particular also use Sow, a custom tag with a unique name is needed to only Reap those values that were Sown by our function, but not the code it executes. Since Module naturally produces (temporary) symbols with unique name, I simply used a Module - generated variable without a value, as a tag. This is a generally useful technique.
To be able to collect the results in the case of Abort[] issued by the user interactively or in the code, we wrap the Do loop in CheckAbort. The code that is executed on Abort[] ({} here) is largely arbitrary in this approach, since the collection of results is anyway done by Sow and Reap, although may be useful in a more elaborate version that would save the result into some variable provided by the user and then re-issue the Abort[] (the functionality not currently implemented).
As a result, we get into a variable indexedRes a flat list of the form
{{expr1, {ind11,ind21,...indn1}},...,{exprk, {ind1k,ind2k,...indnk}}
where the results are grouped with the corresponding index combination. We need these index combinations to reconstruct the multi-dimensional resulting list from a flat list. The way to do it is to repeatedly split the list according to the value of i-th index. The function SplitBy has this functionality, but we need to provide a list of functions to be used for splitting steps. Since the index of i-th iterator index in the sublist {expr,{ind1,...,indn}} is 2,i, the function to do the splitting at i-th step is #[[2, i]]&, and we need to construct the list of such functions dynamically to feed it to SplitBy. Here is an example:
In[46]:= Table[With[{i = i}, Function[Slot[1][[2, i]]]], {i, 5}]
Out[46]= {#1[[2, 1]] &, #1[[2, 2]] &, #1[[2, 3]] &, #1[[2, 4]] &, #1[[2, 5]] &}
The With[{i=i},body] construct was used to inject the specific values of i inside pure functions. The alternatives to inject the value of i into Function do exist, such as e.g.:
In[75]:=
Function[Slot[1][[2, i]]] /. Map[List, Thread[HoldPattern[i] -> Range[5]]]
Out[75]= {#1[[2, 1]] &, #1[[2, 2]] &, #1[[2, 3]] &, #1[[2, 4]] &, #1[[2, 5]] &}
or
In[80]:= Block[{Part}, Function /# Thread[Slot[1][[2, Range[5]]]]]
Out[80]= {#1[[2, 1]] &, #1[[2, 2]] &, #1[[2, 3]] &, #1[[2, 4]] &, #1[[ 2, 5]] &}
or
In[86]:= Replace[Table[{2, i}, {i, 5}], {inds__} :> (#[[inds]] &), 1]
Out[86]= {#1[[2, 1]] &, #1[[2, 2]] &, #1[[2, 3]] &, #1[[2, 4]] &, #1[[ 2, 5]] &}
but are probably even more obscure (perhaps except the last one).
The resulting nested list has a proper structure, with sublists {expr,{ind1,...,indn}} being at level -3 (third level from the bottom). By using Map[First,lst,{-3}], we remove the index combinations, since the nested list has been reconstructed already and they are no longer needed. What remains is our result - a nested list of resulting expressions, whose structure corresponds to the structure of a similar nested list produced by Table. The last statement is wrapped in AbortProtect - just in case, to make sure that the result is returned before the possible Abort[] fires.
Example of use
Here is an example where I pressed Alt+. (Abort[]) soon after evaluating the command:
In[133]:= abortableTable[N[(1+1/i)^i],{i,20000}]//Short
Out[133]//Short= {2.,2.25,2.37037,2.44141,<<6496>>,2.71807,2.71807,2.71807}
It is almost as fast as Table:
In[132]:= abortableTable[N[(1+1/i)^i,20],{i,10000}]//Short//Timing
Out[132]= {1.515,{2.0000000000000000000,2.2500000000000000000,<<9997>>,2.7181459268252248640}}
In[131]:= Table[N[(1+1/i)^i,20],{i,10000}]//Short//Timing
Out[131]= {1.5,{2.0000000000000000000,2.2500000000000000000,<<9997>>,2.7181459268252248640}}
But it does not auto-compile while Table does:
In[134]:= Table[N[(1+1/i)^i],{i,10000}]//Short//Timing
Out[134]= {0.,{2.,2.25,2.37037,2.44141,<<9993>>,2.71815,2.71815,2.71815}}
One can code the auto-compilation and add it to the above solution, I just did not do it since it will be a lot of work to do it right.
EDIT
I rewrote the function to make some parts both more concise and easier to understand. Also,
it is about 25 % faster than the first version, on large lists.
ClearAll[abortableTableAlt];
SetAttributes[abortableTableAlt, HoldAll];
abortableTableAlt[expr_, iter : {_Symbol, __} ..] :=
Module[{indices, indexedRes, sowTag, depth = Length[Hold[iter]] - 1},
Hold[iter] /. {sym_Symbol, __} :> sym /. Hold[syms__] :> (indices := {syms});
indexedRes = Replace[#, {x_} :> x] &# Last#Reap[
CheckAbort[Do[Sow[{expr, indices}, sowTag], iter], Null],sowTag];
AbortProtect[
SplitBy[indexedRes, Array[Function[x, #[[2, x]] &], {depth}]][[##,1]] & ##
Table[All, {depth + 1}]
]];
Unfortunately no. If you want to do something like lst=Table[f[i],{i,1,10000}] so that if aborted you still have results, you could do
Clear[lst2];
lst2 = {};
(Do[lst2 = {lst2, f[i]}, {i, 1, 10000}];
lst2=Flatten[lst2];) // Timing
which, for undefined f, takes 0.173066s on my machine, while lst = Table[f[i], {i, 1, 100000}] takes roughly 0.06s (ie, Table it is 3 times faster at the expense of not being interruptible).
Note that the obvious "interruptible" solution, lst = {};
Do[AppendTo[lst, f[i]], {i, 1, 100000}] takes around 40s, so don't do that: use linked lists and flatten at the end, like in my first example (however, that will break if f[i] returns a list, and more care is then needed).
Another solution is to export results of intermediate computations to a running log file as described in this answer by WReach (see the "File-backed In-memory Approach" section). With this you will newer loose results of intermediate computations and will always be able to investigate what is computed so far.
P.S. I think usage of Monitor as suggested in this recent Mathematica tip on twitter is also useful in such cases:
Monitor[Table[Integrate[1/(x^n + 1), x], {n, 20}],
ProgressIndicator[n, {1, 20}]]
I want to describe an issue I have been having with Plot using With to keep defined parameters 'local'. I am not necessarily asking for a fix: the problem I have is one of understanding.
Sometimes I use a construction such as the following to obtain a Plot:
Method 1
plot1 = With[{vmax = 10, km = 10},
Plot[Evaluate#((vmax x)/(km + x)), {x, 0, 100},
AxesOrigin -> {0, 0}]]
I like this method, and it is reasonably clear even to non-Mathematica users exactly what is going on.
When the equations to be plotted become more complex, I like to define them external to the plot (using SetDelayed). For example:
f[x_] := (vmax x)/(km + x)
However, the following does not work
Method 2
plot2 = With[{vmax = 10, km = 10},
Plot[Evaluate#f[x], {x, 0, 100}, AxesOrigin -> {0, 0}]]
I have always naively thought that it should. However, based on the Help statement that
Plot treats the variable x as local,
effectively using Block
I have used various workarounds, mostly something like the following
Method 3
plot3 = Plot[With[{vmax = 10, km = 10}, Evaluate#f[x]], {x, 0, 100},
AxesOrigin -> {0, 0}]
This one seems very awkward, and usually requires further explanation even to Mathematica users.
Plot outputs
However, recently I found out by chance that substituting Block for With in Method 2 works exactly as expected.
I can, for example, do something like the following (which to me seems a very versatile approach):
plot4 = Block[{vmax = {10, 10, 10}, km = { 10, 100, 1000}},
Plot[Evaluate#f[x], {x, 0, 100}, AxesOrigin -> {0, 0},
PlotStyle -> {Red, Green, Blue}]]
giving
My questiions are as follows. What is the explanation for the difference in behaviour with With in Method 1 and 2? Should I have expected Method 2 not to work? Furthermore, what is the explanation for the difference in behaviour with Block and With in Method 2? Should I have been able to predict that Block would work?
Funnily enough many workarounds have been suggested to me by those more experienced than I, but nobody suggested using Block.
Finally, I need to keep vmax and km local.(They have been defined algebraically elsewhere)
Your question is not so much about Plot as it is about how the scoping constructs work. The main confusion here is due to the differences between lexical and dynamic scoping. And the main culprit is this definition:
f[x_] := (vmax x)/(km + x)
The problem with it is that it makes f implicitly depend on the global symbols (variables) vmax and km. I am very much against this sort of constructs since they lead to infinite confusion. Now, what happens can be illustrated with the following example:
In[55]:= With[{vmax =1, km = 2},f[x]]
Out[55]= (vmax x)/(km+x)
To understand why this happens, one must understand what the lexical scoping means. We know that With has a HoldAll attribute. The way it works is that it looks are what is literally inside it, and substitutes variables found literally in the body with their values from the declaration list. This happens during the variable-binding stage, and only then it lets the body to evaluate. From this, it is clear that the following will work:
In[56]:= With[{vmax =1, km = 2},Evaluate[f[x]]]
Out[56]= x/(2+x)
This worked because Evaluate overrides the "part" of HoldAll attribute of With, forcing the body to evaluate before anything else (variable binding, and subsequent body evaluation). Therefore, it would be completely equivalent to use just With[{vmax = 1, km = 2}, (vmax x)/(km + x)] above, as you can see with Trace. The next part of the puzzle is why
With[{vmax = 10, km = 10}, Plot[Evaluate#f[x], {x, 0, 100}, AxesOrigin -> {0, 0}]]
does not work. This is because this time we do not evaluate the body first. The presence of Evaluate affects only f[x] inside Plot, but not the evaluation of Plot itself inside With. This is illustrated by
In[59]:= With[{vmax = 10, km = 10}, q[Evaluate#f[x]]]
Out[59]= q[(vmax x)/(km + x)]
Moreover, we do not want Plot to evaluate first, since then the values of vmax and km will not be defined. However, all that With sees is f[x], and since the parameters vmax and km are not literally present in there (lexical scoping, remember), no substitution will be made. Should we use Block here, and things will work, because Block uses dynamic scoping, meaning that it redefines values in time (part of the execution stack if you wish), rather than in place. Therefore, using Block[{a =1, b =2}, ff[x]] where ff implicitly depends on a and b is (roughly) equivalent to a=1;b=2;ff[x] (with the difference that a and b resume their global values after the Block scope is left). So,
In[60]:= Block[{vmax = 10, km = 10}, q[Evaluate#f[x]]]
Out[60]= q[(10 x)/(10 + x)]
To make the With version work, you'd have to inject the expression for f[x] (r.h.s), for example like so:
In[63]:= Unevaluated[With[{vmax = 10, km = 10}, q[f[x]]]] /. DownValues[f]
Out[63]= q[(10 x)/(10 + x)]
Note that this won't work:
In[62]:= With[{fx = f[x]}, With[{vmax = 10, km = 10}, q[fx]]]
Out[62]= q[(vmax x)/(km + x)]
But the reason here is quite subtle: while outer With evaluates before the inner one, it spots the variable name conflicts and renames its variables. Rules are much more disruptive, they don't respect inner scoping constructs.
EDIT
If one insists on nested With-s, here is how one can fool the name conflict resolution mechanism of With and make it work:
In[69]:= With[{fx = f[x]}, With ## Hold[{vmax = 10, km = 10}, q[fx]]]
Out[69]= q[(10 x)/(10 + x)]
Since outer With can no longer detect the presence of inner With (using Apply[With,Hold[...]] makes the inner With effectively dynamically generated), it does not make any renamings, and then it works. This is a general trick to fool lexical scoping name resolution mechanism when you don't want renaming, although the necessity to use it usually indicates a bad design.
END EDIT
But I digressed. To summarize, making your second method work is quite hard and requires really weird constructs like
Unevaluated[ With[{vmax = 10, km = 10}, Plot[Evaluate#f[x], {x, 0, 100},
AxesOrigin -> {0, 0}]]] /. DownValues[f]
or
With[{fx = f[x]},
With ## Hold[{vmax = 10, km = 10},
Plot[Evaluate#fx, {x, 0, 100}, AxesOrigin -> {0, 0}]]]
Once again: all this is because With must "see" the variables explicitly in the code, to make replacements. In contrast, Block does not need that, it replaces values dynamically at the moment of evaluation, based on their modified global values, as if you made assignments, this is why it works.
Now, the real culprit is your definition of f. You could have avoided all these troubles should you have defined your f with explicit parameter-passing:
ff[x_, vmax_, km_] := (vmax x)/(km + x)
Now, this works out of the box:
With[{vmax = 10, km = 10},
Plot[Evaluate#ff[x, vmax, km], {x, 0, 100}, AxesOrigin -> {0, 0}]]
because the parameters are explicitly present in the function call signature, and so are visible to With.
To summarize: what you observed is a consequence of the interplay between lexical and dynamic scoping. Lexical scoping constructs must "see" their variables explicitly in the code at the variable-binding stage (before evaluation), or they won't be effective. Dynamic scoping effectively modifies values of symbols, and is in this sense less demanding (the price you pay is that the code using lots of dynamic scoping is harder to understand, since it mixes state and behavior). The main reason for trouble is the function definition that makes implicit dependencies on global symbols (that are not in the formal parameter list of the function). It is best to avoid such constructs. It is still possible to make things work, but this is considerably more complicated (as was demonstrated above), and, at least for the case at hand, for no good reason.
Just two comments:
using Block, you don't need to use Evaluate. That is, Block[{vmax = 10, km = 2}, Plot[f[x], {x, 0, 100}] will work.
Another way to do this is to define substitution rules:
rule = {vmax -> 10, km -> 10}; Plot[f[x] /. rule, {x, 0, 100}]
The advantage is that you can re-use the rule in other statements.
In addition, you can define multiple substition rules for different cases: rule1 = {vmax -> 10, km -> 10}, rule2 = {vmax -> 2, km -> 2}
Does mathematica have something like "select any" that gets any element of a list that satisfies a criterion?
If you just want to return after the first matching element, use the optional third argument to Select, which is the maximum number of results to return. So you can just do
Any[list_List, crit_, default_:"no match"] :=
With[{maybeMatch = Select[list, crit, 1]},
If[maybeMatch =!= {},
First[maybeMatch],
default]
Mathematica lacks a great way to signal failure to find an answer, since it lacks multiple return values, or the equivalent of Haskell's Maybe type. My solution is to have a user-specifiable default value, so you can make sure you pass in something that's easily distinguishable from a valid answer.
Well, the downside of Eric's answer is that it does execute OddQ on all elements of the list. My call is relatively costly, and it feels wrong to compute it too often. Also, the element of randomness is clearly unneeded, the first one is fine with me.
So, how about
SelectAny[list_List, criterion_] :=
Catch[Scan[ If[criterion[#], Throw[#, "result"]] &, list];
Throw["No such element"], "result"]
And then
SelectAny[{1, 2, 3, 4, 5}, OddQ]
returns 1.
I still wish something were built into Mathematica. Using home-brew functions kind of enlarges your program without bringing much direct benefit.
The Select function provides this built-in, via its third argument which indicates the maximum number of items to select:
In[1]:= Select[{1, 2, 3, 4, 5}, OddQ, 1]
Out[1]= {1}
When none match:
In[2]:= Select[{2, 4}, OddQ, 1]
Out[2]= {}
Edit: Oops, missed that nes1983 already stated this.
You can do it relatively easily with Scan and Return
fstp[p_, l_List] := Scan[ p## && Return## &, l ]
So
In[2]:= OddQ ~fstp~ Range[1,5]
Out[2]= 1
In[3]:= EvenQ ~fstp~ Range[1,5]
Out[3]= 2
I really wish Mathematica could have some options to make expressions evaluated lazily. In a lazy language such as Haskell, you can just define it as normal
fstp p = head . filter p
There's "Select", that gets all the elements that satisfy a condition. So
In[43]:= Select[ {1, 2, 3, 4, 5}, OddQ ]
Out[43]= {1, 3, 5}
Or do you mean that you want to randomly select a single matching element? I don't know of anything built-in, but you can define it pretty quickly:
Any[lst_, q_] :=
Select[ lst, q] // (Part[#, 1 + Random[Integer, Length[#] - 1]]) &
Which you could use the same way::
In[51]:= Any[ {1, 2, 3, 4, 5}, OddQ ]
Out[51]= 3