Skip to content

Commit 727c493

Browse files
author
czheo
committed
add as_a
1 parent 4137acf commit 727c493

File tree

3 files changed

+25
-10
lines changed

3 files changed

+25
-10
lines changed

README.md

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -158,15 +158,15 @@ from syntax_sugar import INF, take, each
158158
for i in 1 /to/ INF:
159159
print(i)
160160

161-
list(1 /to/ INF /take/ 5)
161+
1 /to/ INF /take/ 5 /as_a/ list
162162
# there is a `take` functon which is similar to itertools.islice
163163
# return [1, 2, 3, 4, 5]
164164

165-
list(0 /to/ -INF /step/ 2 /take/ 5)
165+
0 /to/ -INF /step/ 2 /take/ 5 /as_a/ list
166166
# also works with negative infinity.
167167
# return [0, -2, -4, -6, -8]
168168

169-
list((1 /to/ 3) * (4 /to/ 6))
169+
(1 /to/ 3) * (4 /to/ 6) /as_a/ list
170170
# all combinations of [1..3] * [4..6]
171171
# return [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
172172

@@ -188,6 +188,20 @@ def push(lst, x):
188188
[] /push/ 1 /push/ 2 /push/ 3
189189
# returns [1,2,3]
190190
```
191+
192+
You can also do
193+
194+
```
195+
def push(lst, x):
196+
lst.append(x)
197+
return lst
198+
199+
ipush = push /as_a/ infix
200+
201+
[] /ipush/ 1 /ipush/ 2 /ipush/ 3
202+
# returns [1,2,3]
203+
```
204+
191205
<!---
192206
### stream
193207

syntax_sugar/infix.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
__all__ = [
55
'infix',
66
'is_a',
7+
'as_a',
78
'to',
89
'step',
910
'INF',
@@ -26,29 +27,26 @@ def __rtruediv__(self, left):
2627
is_a = infix(isinstance)
2728
has = infix(hasattr)
2829

30+
@infix
31+
def as_a(obj, clazz):
32+
return clazz(obj)
33+
2934
@infix
3035
def to(start, end):
3136
return Iterator(Range(start, end))
3237

3338
@infix
3439
def step(obj, step):
35-
# ex. -2 step -> 2 step
3640
step = abs(step)
3741
obj = Iterator(obj) if not obj /is_a/ Iterator else obj
3842
return obj.slice(step=step)
3943

4044
@infix
4145
def take(obj, n):
42-
# ex. n = 3
43-
# [0, 1, 2, 3, 4, 5, 6] =>
44-
# [0, 1, 2]
4546
obj = Iterator(obj) if not obj /is_a/ Iterator else obj
4647
return obj.slice(stop=n)
4748

4849
@infix
4950
def drop(obj, n):
50-
# ex. n = 3
51-
# [0, 1, 2, 3, 4, 5, 6] =>
52-
# [3, 4, 5, 6]
5351
obj = Iterator(obj) if not obj /is_a/ Iterator else obj
5452
return obj.slice(start=n)

tests/test_infix.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,6 @@ def test_is_a():
112112
for value, types in values_types_wrong:
113113
for type in types:
114114
assert not value /is_a/ type
115+
116+
def test_as_a():
117+
assert 1 /as_a/ str == '1'

0 commit comments

Comments
 (0)