This commit is contained in:
blueloveTH 2023-04-24 18:41:12 +08:00
parent 2037b6f6c3
commit 07a0122f4b
4 changed files with 13 additions and 60 deletions

View File

@ -1,30 +0,0 @@
---
icon: dot
---
# ternary op
Ternary operator is a short hand `if...else`.
pkpy supports both c and python style ternary.
## Syntax
```
<condition> ? <true_expr> : <false_expr>
```
```
<true_expr> if <condition> else <false_expr>
```
## Example
```python
a = 1
s = a == 1 ? "a is 1" : "a is not 1"
print(s) # a is 1
# which equals to
s = "a is 1" if a == 1 else "a is not 1"
```

View File

@ -5,20 +5,20 @@ def print(*args, sep=' ', end='\n'):
def round(x, ndigits=0):
assert ndigits >= 0
if ndigits == 0:
return x >= 0 ? int(x + 0.5) : int(x - 0.5)
return int(x + 0.5) if x >= 0 else int(x - 0.5)
if x >= 0:
return int(x * 10**ndigits + 0.5) / 10**ndigits
else:
return int(x * 10**ndigits - 0.5) / 10**ndigits
def abs(x):
return x < 0 ? -x : x
return -x if x < 0 else x
def max(a, b):
return a > b ? a : b
return a if a > b else b
def min(a, b):
return a < b ? a : b
return a if a < b else b
def all(iterable):
for i in iterable:

View File

@ -104,7 +104,6 @@ class Compiler {
rules[TK("&")] = { nullptr, METHOD(exprBinaryOp), PREC_BITWISE_AND };
rules[TK("|")] = { nullptr, METHOD(exprBinaryOp), PREC_BITWISE_OR };
rules[TK("^")] = { nullptr, METHOD(exprBinaryOp), PREC_BITWISE_XOR };
rules[TK("?")] = { nullptr, METHOD(exprTernary), PREC_TERNARY };
rules[TK("if")] = { nullptr, METHOD(exprTernary), PREC_TERNARY };
rules[TK(",")] = { nullptr, METHOD(exprTuple), PREC_TUPLE };
rules[TK("not in")] = { nullptr, METHOD(exprBinaryOp), PREC_TEST };
@ -253,25 +252,14 @@ class Compiler {
void exprTernary(){
auto e = make_expr<TernaryExpr>();
if(prev().type == TK("if")){
e->true_expr = ctx()->s_expr.popx();
// cond
parse_expression(PREC_TERNARY + 1);
e->cond = ctx()->s_expr.popx();
consume(TK("else"));
// if false
parse_expression(PREC_TERNARY + 1);
e->false_expr = ctx()->s_expr.popx();
}else{ // ?:
e->cond = ctx()->s_expr.popx();
// if true
parse_expression(PREC_TERNARY + 1);
e->true_expr = ctx()->s_expr.popx();
consume(TK(":"));
// if false
parse_expression(PREC_TERNARY + 1);
e->false_expr = ctx()->s_expr.popx();
}
e->true_expr = ctx()->s_expr.popx();
// cond
parse_expression(PREC_TERNARY + 1);
e->cond = ctx()->s_expr.popx();
consume(TK("else"));
// if false
parse_expression(PREC_TERNARY + 1);
e->false_expr = ctx()->s_expr.popx();
ctx()->s_expr.push(std::move(e));
}

View File

@ -17,9 +17,4 @@ assert bool(1) == True
assert bool([]) == False
assert bool("abc") == True
assert bool([1,2]) == True
assert bool('') == False
# test ?:
a = 5
assert ((a > 3) ? 1 : 0) == 1
assert ((a < 3) ? 1 : 0) == 0
assert bool('') == False