Let' s suppose I call a function with the Greater symbol ">" an argument:
findb[x^2 - 10, ">", 0]
Instead of testing within the function body what the second argument is (the usual design) I want it to replace directly every expression where it appears:
findb[exp_Plus, ptest_String, value_?NumberQ] :=
Module[{},
x /. Flatten[{FindInstance[(exp ToExpression[ptest] value) &&
x != 0 , x, Reals]}]]
As this cannot work with the ToExpression built-in what is the way to achieve this result?
As hinted by #agentp here is an answer which is OK:
findb[exp_Plus, ptest_String, value_?NumberQ] := Module[{},
x /.Flatten[{FindInstance[(ToExpression[
StringJoin[ToString[exp, InputForm], ptest,
ToString[value]]]) && x != 0 , x, Reals]}]]
However I find that very verbose. Can it be improved?
Alternate approach, assuming you support a discrete list of allowable operators:
Switch[ ptest ,
">" , exp > value ,
"<" , exp < value , ... ]
not elegant, but it may be the safest most robust approach.
Related
I want to set the value of a equal to the index found unless that index is zero, in which case I want to set it to some number minus that value. I am wondering if it is possible to perform this action (taken from python) in Ruby:
a='/-123456789X'.find(y)or 99-x
Does anyone know of a good way to do this?
Try this one. Given x and y
a = "/-123456789X".index(y) || 99 - x
In python string.find(other) will return the index of other or -1 if other does not exist in string.
In ruby string.index(other) will return the index of other or nil if other does not exist in string.
"Truthy" and "Falsey" values:
ruby acknowledges nil as "falsey" and 0 as "truthy"; but
python acknowledges 0 as "falsey" and -1 as "truthy"
So your current python code has 3 possible return values:
-1 (non-existent sub-string)
99 - x (existent sub-string starting with '/')
n (index of existent sub-string that does not start with '/')
In order to achieve an equivalent result in ruby your code could look like this:
str = '/-123456789X'
a = if y.start_with?('/') && str.index(y)
99 - x
else
str.index(y) || -1
end
Other alternatives include:
# Ruby >= 2.5 using `String#match?
str.match?(/\A#{y}/) ? 99 - x : str.index(y) || -1
That being said your actual request "I want to set the value of a equal to the index found unless that index is zero, in which case I want to set it to some number minus that value" seems a little different and I am not sure if this means that x is "that value" and what x should represent in that case.
Should x be the begining index?
Should x be the ending index?
I am new in prolog i have a code that i want to read from file then parse this is the code here
var x;
x <- (5 * 2);
return (x + 1).
now in prolog i want to tokenize this like this first
[’var’, ’x’, ’;’, ’x’,’<-’, ’(’, 5, ’*’, 2, ’)’, ’;’, ’return’, ’(’, ’x’, ’+’, 1, ’)’, ’.’]
the i want to implement predicate
parse(+TokenList, -AST)
then again
evaluate(+AST, -Number)
using SWIProlog
The parser should not allow the keywords of the language (e.g., the arithmetic operators, <-,
var, return) as variable identifiers
You can try tokenize_atom, to see if it fits your requirements.
Otherwise, bite the bullet and try to write your own DCG...
I would like to know, how expressions are parsed when are mixed with control flow.
Let's assume such syntax:
case
when a == Method() + 1
then Something(1)
when a == Other() - 2
then 1
else 0
end
We've got here two conditional expressions, Method() + 1, Something(1) and 0. Each can be translated to postfix by Shunting-yard algorithm and then easily translated into AST. But is it possible to extend this algorithm to handle control - flow also? Or are there other approaches to solve such mixing of expressions and control flows?
another example:
a == b ? 1 : 2
also how can I classify such expression: a between b and c, can I say that between is three arguments function? Or is there any special name for such expressions?
You can certainly parse the ternary operator with an operator-precedence grammar. In
expr ? expr : expr
the binary "operator" here is ? expr :, which conveniently starts and ends with an operator token (albeit different ones). To adapt shunting yard to that, assign the right-precedence of ? and the left-precedence of : to the precedence of the ?: operator. The left-precedence of ? and the right-precedence of : are ±∞, just like parentheses (which, in effect, they are).
Since the case statement is basically repeated application of the ternary operator, using slightly different spellings for the tokens, and yields to a similar solution. (Here case when and end are purely parenthetic, while then and the remaining whens correspond to ? and :.)
Having said that, it really is simpler to use an LALR(1) parser generator, and there is almost certainly one available for whatever language you are writing in.
It's clear that both the ternary operator and OP's case statement are operator grammars:
Ternary operator:
ternary-expr: non-ternary-expr
| non-ternary-expr '?' expr ':' ternary-expr
Normally, the ternary operator will be lower precedence from any other operator and associate to the right, which is how the above is written. In C and other languages ternary expressions have the same precedence as assignment expressions, which is straightforward to add. That results in the relationships
X ·> ?
? <· X
? ·=· :
X ·> :
: <· X
Case statement (one of many possible formulations):
case_statement: 'case' case_body 'else' expr 'end'
case_body: 'when' expr 'then' expr
| case_body 'when' expr 'then' expr
Here are the precedence relationships for the above grammar:
case <· when
case ·=· else
when <· X (see below)
when ·=· then
then ·> when
then ·> else
else <· X
else ·=· end
X ·> then
X ·> when
X ·> end
X in the above relations refers to any binary or unary operator, any value terminal, ( and ).
It's straightforward to find left- and right-precedence functions for all of those terminals; the pattern will be similar to that of parentheses in a standard algebraic grammar.
The Shunting-yard algorithm is for expressions with unary and binary operators. You need something more powerful such as LL(1) or LALR(1) to parse control flow statements, and once you have that it will also handle expressions as well. No need for the Shunting-yard algorithm at all.
I would like to use Iverson bracket (ie. mapping true => 1, false => 0) in the XPath expression.
Example: instead of writing
someNumber+(if(elem1/elem2[#attr='123'])then(1)else(0)))*someOtherNumber
I would like to write (but somehow without the "Iverson")
someNumber+Iverson(elem1/elem2[#attr='123'])*someOtherNumber
The following doesn't work:
someNumber+[elem1/elem2[#attr='123']]*someOtherNumber
Casting to boolean works:
someNumber+boolean(elem1/elem2[#attr='123'])*someOtherNumber
Is there a more simple syntax than "if(...)then(1)else(0)" or "boolean(...)"?
Iverson
Interestingly, in XPath you already use a version of the Iverson bracket syntax with predicates in [#attr='123'] or [#attr], which returns true if its EBV is true. But if it evaluates to a number, it will return the nth item from the sequence.
For the discussion, let's replace your expression elem1/elem2[#attr='123'] with EXPR for brevity, and the rest like:
X + EXPR * Y
Where the idea is to get as close as possible to the Iverson syntax for EXPR.
XPath 2.0
Your expression requires less parentheses:
X + if(EXPR) then 1 else 0 * Y
This can also be written as the following, assuming false-value of EXPR is an empty sequence:
X + (EXPR, 1, 0)[2] * Y
Is there a more simple syntax than "boolean(...)"?
You suggested the boolean(EXPR) function, but as you mentioned in the comments, this will not work, you need to convert it to a number, for instance with:
X + number(boolean(EXPR)) * Y
I think the shortest version in XPath 2.0 is the empty-sequence dismissal approach, but it may not always work, it requires the first item to return the empty sequence.
If you have a validating processor that sets the element as boolean, you can use:
X + number(EXPR) * Y
Or if typed as a number with valid values 0 and 1, just:
EXPR
XPath 3.0
Let's see if with the new XPath 3.0 syntax we can get even simpler:
let $Iv := function($i) { number(boolean($i)) }
return X + $Iv(EXPR) * Y
With XQuery and XSLT, but also XPath, you can declare this variable globally, which changes the expression into:
X + $Yv(EXPR) * Y
But you'll still have to deal with the parentheses, but keep reading...
XPath 3.1
In 3.1, the arrow operator has been introduced, which allows your original example to be written as:
X + EXPR=>boolean()=>number() * Y
Given that we now have a global variable with a function item, we can do:
X + EXPR=>$Iv() * Y
Other approach
Since setting a global variable to an anonymous function is nothing more than creating a function, we can also declare a function in XQuery or XSLT. Something like:
X + EXPR=>i:v() * Y
I'd like to know how many "comparings" in Ruby are connected. Do I need the brackets for the following expression?
(x != y) && z
My guess is no, but I'm not 100% familiar on how Ruby evaluates such things. I would say: comparing operators (don't know how they are called correctly) like !=, == etc. are evaluated first, and after this the combination operators like && and || are evaluated.
Where do I find more informations about this?
No you don't need the parentheses: != has higher precedence than &&.
Refer to the precedence table for more info.