Skip to content

Instantly share code, notes, and snippets.

@agumonkey
Created February 7, 2019 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agumonkey/4c9cd950abe30a3d26cd771804508697 to your computer and use it in GitHub Desktop.
Save agumonkey/4c9cd950abe30a3d26cd771804508697 to your computer and use it in GitHub Desktop.
Trying to make a refill buffer/display .. functionally
class Width:
def __init__(self, w):
self.l = []
self.w = w
def put(self, d):
self.l.append(d)
def __repr__(self):
"""
l [a,b,...]
f,r = width[w](a,b,...)
l = f
yield l
repeat until witdh[w] fails
"""
w = self.w
# def widthed(w,l):
# s = ''
# i = 0
# while len(s) < w and i < len(l):
# s += l[i]
# if len(s) >= w:
# d = w - len(s)
# s = s[:-d]
# break
# else:
# i += 1
def take_while(p,l):
if l:
a,*b = l
if p(a):
yield a
yield from take_while(p,b)
def fip(l,f):
# or fap..
# or mip..
if l:
a,*b = l
yield (a,f(a))
yield from fip(b,f)
def summing(z,s):
_ = z
def summing_f(v):
nonlocal _
_ = s(_,v)
return _
return summing_f
def fip_test():
inp = 'one ajef oefi foejfe oj'.split(' ')
andthen = lambda a,x: a+len(x)
summer = summing(0, andthen)
return list(fip(inp, summer))
def sumto(s):
i = 0
def sumto_f(v):
l = len(v)
nonlocal i
i += l
return i <= s
return sumto_f
def take_while_then(p,t,l):
if l:
a,*b = l
if p(a):
yield a
yield from take_while_then(p,t,b)
else:
yield t(a,b)
def twt_test():
limit = sumto(8)
lastly = lambda e,r: (e,r)
inp = ['a','a','a','a','babababa', 'ca',]
for e in take_while_then(limit, lastly, inp):
print(e)
# not bad but not great
# take_while_then(_,t,_) t needs more data
# maybe I need a super predicate
# callable => a -> bool
# rest => parameter and state
# idea: per char chunker
# for chunk ch, for char c: if l.size < w: put(l,c) else push old, new l, put(l,c)
# idea: resplitted
# [aaaa, bbbbbbb, ccccc, dddddddddd, e, ...]
# stateful f<s>
# f<s> aaaa bbbbbbb -> (aaaabbb, bbbb) ...
def width(w,l,a=None):
# w, a, [] = yield a
# w, a < w, [...] = rec
# w, a = w, [...] = yield a
# w, a > w, [...] = yield a-d ; rec w, a-d, [...]
if not l:
yield a
elif len(a) < w:
yield from width(w,l,a)
elif len(a) == w:
yield a
elif len(a) > w:
d = len(a) - w
yield a[:-d]
yield from width(w,l,a[-d:])
# def g(x):
# if not x:
# n = x+10
# yield [n]*n
# else:
# yield x
# yield from g(x-1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment