-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
73 lines (58 loc) · 1.54 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from __future__ import with_statement
def lfind(ls, pred):
for i in range(0, len(ls)):
if pred(ls[i]): return ls[i]
def lindex(ls, pred):
for i in range(0, len(ls)):
if pred(ls[i]): return i
def interleave(*args):
for idx in range(0, max(len(arg) for arg in args)):
for arg in args:
try:
yield arg[idx]
except IndexError:
continue
def tuplize(*args):
return [[arg[idx] for arg in args] for idx in range(0, max(len(arg) for arg in args))]
def times(num, fn):
for i in range(0,num):
fn(i)
def each(ls, fn):
for l in ls:
fn(l)
def subdivide(ls, increment):
acc = []
cursor = 0
while cursor < len(ls):
acc.append(ls[cursor:(cursor+increment)])
cursor += increment
return acc
def forall(ls, pred):
return not lfind(ls, lambda e: not pred(e))
def ident(x): return x
def assertAll(*conditions):
assert forall(conditions, ident)
def read_file(path):
text = ""
with open(path) as f:
for line in f:
text += line
return text
def partial(fn, *args):
def p(*rest):
total = args + rest
return fn(*total)
return p
def fixed_point(data, fn):
return data == fn(data)
def float_eq(a,b):
return a - b < 0.001
def swap(ls, old, new):
index = ls.index(old)
ls[index] = new
def reduce_left(ls, fn):
length = len(ls)
last = fn(ls[0], ls[1])
for i in range(2, length):
last = fn(last, ls[i])
return last