I want to match expression who's head differs from f.
This works
[In] !MatchQ[t[3], x_ /; Head[x] == f]
[Out] True
But not this
[In] MatchQ[t[3], x_ /; Head[x] != f]
[Out] False
Why does the second solution not work? How can I make it work?
Why this does not work: you must use =!= (UnsameQ), rather than != (Unequal) for structural comparisons:
In[18]:= MatchQ[t[3],x_/;Head[x]=!=f]
Out[18]= True
The reason can be seen by evaluating this:
In[22]:= Head[t[3]]!=f
Out[22]= t!=f
The operators == (Equal) and != (Unequal) do evaluate to themselves, when the fact of equality (or inequality) of the two sides can not be established. This makes sense in a symbolic environment. I considered this topic in more detail here, where also SameQ and UnsameQ are discussed.
There are also more elegant ways to express the same pattern, which will be more efficient as well, such as this:
MatchQ[t[3],Except[_f]]
Related
Suppose I've defined a few values for a function:
+(value[1] == "cats")
+(value[2] == "mice")
Is it possible to define a function like the following?
(undefined[X] == False) <= (value[X] == Y)
(undefined[X] == True) <= (value[X] does not exist)
My guess is that it can't, for two reasons:
(1) Queries are guaranteed to terminate in Datalog, and you could query for undefined[X] == True.
(2) According to Wikipedia, one of the ways Datalog differs from Prolog is that Datalog "requires that every variable appearing in a negative literal in the body of a clause also appears in some positive literal in the body of the clause".
But I'm not sure, because the terms involved ("terminate", "literal", "negative") have so many uses. (For instance: Does negative literal mean f[X] == not Y or does it mean not (f[X] == Y)? Does termination mean that it can evaluate a single expression like undefined[3] == True, or does it mean it would have found all X for which undefined[X] == True?)
Here another definition of "safe".
A safety condition says that every variable in the body of a rule must occur in at least one positive (i.e., not negated)
atom.
Source: Datalog and Recursive Query Processing
And an atom (or goal) is a predicate symbol (function) along with a list of terms as arguments. (Note that “term” and “atom” are used differently here than they are in Prolog.)
The safety problem is to decide whether the result of a given Datalog program can be guaranteed to be finite even when some source relations are infinite.
For example, the following rule is not safe because the Y variable appears only in a negative atom (i.e. not predicate2(Z,Y)).
rule(X,Y) :- predicate1(X,Z), not predicate2(Z,Y) .
To meet the condition of safety the Y variable should appear in a positive predicate too:
rule(X,Y) :- predicate1(X,Z), not predicate2(Z,Y), predicate3(Y) .
Say we have bool true = (P v Q) -> R
How would I define an operator(or a function), so that the symbols(v, ^, XOR, ->, <->), would call the function that would perform the logic?
So, in example: bool true = P v Q, would call bool or(bool a, bool b)
It is not possible to define arbitrary infix operators in C++, and you also can’t use the name true as a variable name.
However, C++ already provides || for or, && for and, ^ or != for xor (for bools, they’re equivalent), and ! for not. If you want logical implication you’d best use !P || Q, and if you want iff, you should use P == Q.
What's the point of not (!) logic? It seems that you can do everything not can do with all the other logical operators. Is there something that not can do that I am missing?
You won't deny that the NOT-operator is very convenient in a programming language even if the other operators and built-in constants available in that
language render it strictly redundant. Convenience is an adequate justification - in fact it is the justification - for almost all features of all general
programming languages. If we didn't care about convenience - which in programming, means productivity - we could write all programs with a set of
Turing-complete op-codes far smaller even than any assembly language.
The degree of inconvenience you would face in doing without the NOT-operator depends on the programming language you are considering and specifically
on the other operators and built-in-constants that the language provides and their semantics.
In C, for example, the equality operator == exists but there are no built-in constants representing truth and falsity: any integral value all of whose bits are 0 behaves as falsity in boolean operations and all other integral values behave as truth. !cond evaluates to 0 if cond evaluates non-zero and otherwise evaluates to 1. Thus
to say that cond is not true without coding !cond you have to code cond == 0, taking at least 2 keystrokes more.
Like C, C++ has equality and inequality operators but unlike C it represents the boolean truth valiues by the built-in constants true and false. Thus
to say that cond is not true in C++ without coding !cond you must code either cond != true or cond == false, taking at least 5 keystrokes more.
And the cost of doing without the NOT-operator can potentially compound beyond minor inconvenience. Which of the following can you understand first?:
!(p && !q) == (!p || q)
or:
(((p && (q == 0)) == 0) == ((p == 0) || q)
You can implement all logical operators solely with the NAND operator. The NOT operator is for convenience, just like all the others are. In fact, computer systems are implemented solely with either the NAND or the NOR operator. All other operators are abstractions put in place for convenience.
It is convenient, however. Since you mention the "!" operator, I assume you mean boolean operators in general programming languages. Then the not operator is very convenient. Imagine you wanted to express something like "print all names except 'Bob'". You could do that with the != operator, which is a further short-form of !(expression1 == expression2):
if( !(name == 'Bob') ) {
print name
}
I have a following problem.
f[1]=1;
f[2]=2;
f[_]:=0;
dvs = DownValues[f];
this gives
dvs =
{
HoldPattern[f[1]] :> 1,
HoldPattern[f[2]] :> 2,
HoldPattern[f[_]] :> 0
}
My problem is that I would like to extract only definitions for f[1] and f[2] etc but not the general definition f[_], and I do not know how to do this.
I tried,
Cases[dvs, HoldPattern[ f[_Integer] :> _ ]] (*)
but it gives me nothing, i.e. the empty list.
Interestingly, changing HoldPattern into temporary^footnote
dvs1 = {temporary[1] :> 1, temporary[2] :> 2, temporary[_] :> 0}
and issuing
Cases[dvs1, HoldPattern[temporary[_Integer] :> _]]
gives
{temporary[1] :> 1, temporary[2] :> 2}
and it works. This means that (*) is almost a solution.
I do not not understand why does it work with temporary and not with HoldPattern? How can I make it work directly with HoldPattern?
Of course, the question is what gets evaluated and what not etc. The ethernal problem when coding in Mathematica. Something for real gurus...
With best regards
Zoran
footnote = I typed it by hand as replacement "/. HoldPattern -> temporary" actually executes the f[_]:=0 rule and gives someting strange, this excecution I certainly would like to avoid.
The reason is that you have to escape the HoldPattern, perhaps with Verbatim:
In[11]:= Cases[dvs,
Verbatim[RuleDelayed][
Verbatim[HoldPattern][HoldPattern[f[_Integer]]], _]]
Out[11]= {HoldPattern[f[1]] :> 1, HoldPattern[f[2]] :> 2}
There are just a few heads for which this is necessary, and HoldPattern is one of them, precisely because it is normally "invisible" to the pattern-matcher. For your temporary, or other heads, this wouldn't be necessary. Note by the way that the pattern f[_Integer] is wrapped in HoldPattern - this time HoldPattern is used for its direct purpose - to protect the pattern from evaluation. Note that RuleDelayed is also wrapped in Verbatim - this is in fact another common case for Verbatim - this is needed because Cases has a syntax involving a rule, and we do not want Cases to use this interpretation here. So, this is IMO an overall very good example to illustrate both HoldPattern and Verbatim.
Note also that it is possible to achieve the goal entirely with HoldPattern, like so:
In[14]:= Cases[dvs,HoldPattern[HoldPattern[HoldPattern][f[_Integer]]:>_]]
Out[14]= {HoldPattern[f[1]]:>1,HoldPattern[f[2]]:>2}
However, using HoldPattern for escaping purposes (in place of Verbatim) is IMO conceptually wrong.
EDIT
To calrify a little the situation with Cases, here is a simple example where we use the syntax of Cases involving transformation rules. This extended syntax instructs Cases to not only find and collect matching pieces, but also transform them according to the rules, right after they were found, so the resulting list contains the transformed pieces.
In[29]:= ClearAll[a, b, c, d, e, f];
Cases[{a, b, c, d, e, f}, s_Symbol :> s^2]
Out[30]= {a^2, b^2, c^2, d^2, e^2, f^2}
But what if we need to find elements that are themselves rules? If we just try this:
In[33]:= Cases[{a:>b,c:>d,e:>f},s_Symbol:>_]
Out[33]= {}
It doesn't work since Cases interprets the rule in the second argument as an instruction to use extended syntax, find a symbol and replace it with _. Since it searches on level 1 by default, and symbols are on level 2 here, it finds nothing. Observe:
In[34]:= Cases[{a:>b,c:>d,e:>f},s_Symbol:>_,{2}]
Out[34]= {_,_,_,_,_,_}
In any case, this is not what we wanted. Therefore, we have to force Cases to consider the second argument as a plain pattern (simple, rather than extended, syntax). There are several ways to do that, but all of them "escape" RuleDelayed (or Rule) in some way:
In[37]:= Cases[{a:>b,c:>d,e:>f},(s_Symbol:>_):>s]
Out[37]= {a,c,e}
In[38]:= Cases[{a:>b,c:>d,e:>f},Verbatim[RuleDelayed][s_Symbol,_]:>s]
Out[38]= {a,c,e}
In[39]:= Cases[{a:>b,c:>d,e:>f},(Rule|RuleDelayed)[s_Symbol,_]:>s]
Out[39]= {a,c,e}
In all cases, we either avoid the extended syntax for Cases (last two examples), or manage to use it to our advantage (first case).
Leonid, of course, completely answered the question about why your temporary solution works but HoldPattern does not. However, as an answer to your original problem of extracting the f[1] and f[2] type terms, his code is a bit ugly. To solve just the problem of extracting these terms, I would just concentrate on the structure of the left-hand-side of the definition and use the fact that FreeQ searches at all levels. So, defining
f[1] = 1; f[2] = 2; f[_] := 0;
dvs = DownValues[f];
All of the following
Select[dvs, FreeQ[#, Verbatim[_]] &]
Select[dvs, FreeQ[#, Verbatim[f[_]]] &]
Select[dvs, ! FreeQ[#, HoldPattern[f[_Integer]]] &]
yield the result
{HoldPattern[f[1]] :> 1, HoldPattern[f[2]] :> 2}
Provided there are no f[...] (or, for the first version, Blank[]) terms on the right-hand-side of the downvalues of f, then one of the above will probably be suitable.
Based on Simon's excellent solution here, I suggest:
Cases[DownValues[f], _?(FreeQ[#[[1]], Pattern | Blank] &)]
How can I pass values to a given expression with several variables? The values for these variables are placed in a list that needs to be passed into the expression.
Your revised question is straightforward, simply
f ## {a,b,c,...} == f[a,b,c,...]
where ## is shorthand for Apply. Internally, {a,b,c} is List[a,b,c] (which you can see by using FullForm on any expression), and Apply just replaces the Head, List, with a new Head, f, changing the function. The operation of Apply is not limited to lists, in general
f ## g[a,b] == f[a,b]
Also, look at Sequence which does
f[Sequence[a,b]] == f[a,b]
So, we could do this instead
f[ Sequence ## {a,b}] == f[a,b]
which while pedantic seeming can be very useful.
Edit: Apply has an optional 2nd argument that specifies a level, i.e.
Apply[f, {{a,b},{c,d}}, {1}] == {f[a,b], f[c,d]}
Note: the shorthand for Apply[fcn, expr,{1}] is ###, as discussed here, but to specify any other level description you need to use the full function form.
A couple other ways...
Use rule replacement
f /. Thread[{a,b} -> l]
(where Thread[{a,b} -> l] will evaluate into {a->1, b->2})
Use a pure function
Function[{a,b}, Evaluate[f]] ## l
(where ## is a form of Apply[] and Evaluate[f] is used to turn the function into Function[{a,b}, a^2+b^2])
For example, for two elements
f[l_List]:=l[[1]]^2+l[[2]]^2
for any number of elements
g[l_List] := l.l
or
h[l_List]:= Norm[l]^2
So:
Print[{f[{a, b}], g[{a, b}], h[{a, b}]}]
{a^2 + b^2, a^2 + b^2, Abs[a]^2 + Abs[b]^2}
Two more, just for fun:
i[l_List] := Total#Table[j^2, {j, l}]
j[l_List] := SquaredEuclideanDistance[l, ConstantArray[0, Length[l]]
Edit
Regarding your definition
f[{__}] = a ^ 2 + b ^ 2;
It has a few problems:
1) You are defining a constant, because the a,b are not parameters.
2) You are defining a function with Set, Instead of SetDelayed, so the evaluation is done immediately. Just try for example
s[l_List] = Total[l]
vs. the right way:
s[l_List] := Total[l]
which remains unevaluated until you use it.
3) You are using a pattern without a name {__} so you can't use it in the right side of the expression. The right way could be:
f[{a_,b_}]:= a^2+b^2;