add files

This commit is contained in:
Tobias Weise 2024-05-11 23:42:45 +02:00
parent 19722be802
commit 1b1ad5a25d
12 changed files with 423 additions and 0 deletions

54
func.py Normal file
View File

@ -0,0 +1,54 @@
#====================================================================
#===================== Function Decorators ==========================
#====================================================================
def log(f):
def g(*args):
r = f(*args)
print("Calculating: %s(%s) = %s" % ( str(f).split(" ")[1], str(",".join(map(str,list(args)))), str(r)) )
return r
return g
def maybe(f):
def g(*args):
try: return f(*args)
except: return None
return g
def memoize(f):
mem = {}
def g(*args):
if args in mem:
print("Remember: f%s = %s" % (args,mem[args]))
return mem[args]
r = f(*args)
if r != None:
print("Memoize: f%s = %s" % (args,r))
mem[args] = r
return r
return g
#docurry
def curryD(n):
def deco(f):
if n == 1: return f
return lambda x: curry(fix(f, x), n-1)
return deco
#==========================================================
#===================== Functions ==========================
#==========================================================
#======== Composition ================
def fix(f, x):
return lambda *args: f(*([x]+list(args)))
def curry(f, n):
if n == 1: return f
return lambda x: curry(fix(f, x), n-1)
def comp(g,f):
return lambda *args: g(f(*args))

7
func/__init__.py Normal file
View File

@ -0,0 +1,7 @@
from func.func import *
from func.list import *
from func.string import *
from func.io import *

BIN
func/__init__.pyc Normal file

Binary file not shown.

20
func/debug.py Normal file
View File

@ -0,0 +1,20 @@
"""
def log(func):
def new_func(*args):
r = func(*args)
print(">>> " + str(func).split(" ")[1] + str(list(args)) + " -> " + str(r))
return r
return new_func
"""
def log(f):
def g(*args):
r = f(*args)
print("Calculating: %s(%s) = %s" % ( str(f).split(" ")[1], str(",".join(map(str,list(args)))), str(r)) )
return r
return g

46
func/func.py Normal file
View File

@ -0,0 +1,46 @@
# -*- coding: utf-8 -*-
from functools import *
from itertools import *
def compose(g,f):
return lambda *args: g(f(*args))
def comp(*args):
return reduce(compose, args)
def maybe(f):
def g(*args):
try: return f(*args)
except: return None
return g
def memoize(f):
mem = {}
def g(*args):
if args in mem:
print("Remember: f%s = %s" % (args,mem[args]))
return mem[args]
r = f(*args)
if r != None:
print("Memoize: f%s = %s" % (args,r))
mem[args] = r
return r
return g
def curryD(n):
def deco(f):
if n == 1: return f
return lambda x: curry(fix(f, x), n-1)
return deco
def fix(f, x):
return lambda *args: f(*([x]+list(args)))
def curry(f, n):
if n == 1: return f
return lambda x: curry(fix(f, x), n-1)

BIN
func/func.pyc Normal file

Binary file not shown.

58
func/io.py Normal file
View File

@ -0,0 +1,58 @@
try:
from urllib2 import *
except:
from urllib.request import build_opener #py 3
from urllib.error import URLError
from urllib.error import HTTPError
def printLns(ls):
for s in ls:
print(s)
def urlExists(url):
opener = build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
try:
f = opener.open(url)
c = f.read()
f.close()
return True
except HTTPError:
#print("Error 404: "+url)
return False
def downloadFile(url, path):
opener = build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
f = opener.open(url)
c = f.read()
f.close()
f = open(path, "wb")
f.write(c)
f.close()
def readUrl(url):
opener = build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
f = opener.open(url)
c = f.read()
f.close()
return c
def puts(s):
print(str(s))
return s
def writeFile(path, content):
f = open(path, "wb")
f.write(content.encode('latin-1'))
f.close()

49
func/lib.py Normal file
View File

@ -0,0 +1,49 @@
#======= Decoration ========
def log(f):
def g(*args):
r = f(*args)
print(">> %s %s -> %s" % (str(f).split(" ")[1], str(list(args)), str(r)))
return r
return g
#========= Composition =========
def fix1(f, v):
def g(*args):
r = f(*([v]+list(args)))
return r
return g
def curry(func, numArgs):
if numArgs == 1: return func
def f1(v):
return curry(fix1(func, v), numArgs-1)
return f1
def comp(g,f):
def r(*args, **kwargs):
return g(f(*args, **kwargs))
return r
#======== Operations ===========
def add(a, b):
return a + b
def multi(a, b):
return a * b
def Monade():
#Monade, (M a -> (a -> M b) -> M a)
def returm(x):
return [x]
def bind(m, f):
return returm(list(map(f,m)))
return returm, bind

111
func/list.py Normal file
View File

@ -0,0 +1,111 @@
def zipWith(f,ls,xs):
for i in range(len(ls)):
yield f(ls[i],xs[i])
def all(f, ls):
for x in ls:
if not f(x): return False
return True
def splitWhen(f, ls):
b, rs, xs = False, [], []
for x in ls:
if f(x): b = True
if b: xs += [x]
else: rs += [x]
return rs, xs
def tail(ls):
return list(ls)[1:]
def take(n,ls):
for x in ls:
if n < 1: break
yield x
n -= 1
def drop(n,ls):
for x in ls:
if n < 1: yield x
n -= 1
def splitAt(i, ls):
ls = list(ls)
return ls[:i], ls[i:]
def partBy(n, ls):
rs = []
while len(ls) >= n:
xs, ls = splitAt(n,ls)
rs.append(list(xs))
return rs
def concat(ls):
for xs in ls:
for x in xs:
yield x
def dropWhile(f, ls):
b = False
for x in ls:
if not b:
if f(x): continue
else:
b = True
if b:
yield x
def unfold(f, x):
"""
def f(x):
if x > 0: return x, x-1
print(list(unfold(f, 5)))
"""
while True:
r = f(x)
if not r: break
v, x = r
yield v
def nub(ls):
rs = []
for x in ls:
if x not in rs:
rs.append(x)
return rs
def cartProd(ls, xs):
for i in ls:
for x in xs:
if not i is x:
yield i, x
def numEqPrefix(ls, xs):
acc = 0
for i in range(len(ls)):
try:
if ls[i] == xs[i]:
acc += 1
except:
break
return acc
def pairs2list(ls):
rs = []
for a, b in ls:
if not a in rs:
rs.append(a)
if not b in rs:
rs.append(b)
return rs

28
func/monad.py Normal file
View File

@ -0,0 +1,28 @@
class Monad:
def __init__(self, bind, value):
self.__bind = bind
self.__m = unit(value)
def bind(self, f):
self.__m = self.__bind(self.__m, f)
return self
def __lshift__(self, f):
self.__m = self.__bind(self.__m, f)
return self
"""
if __name__ == "__main__":
Monad(bind, 1) << (lambda x: x+10) << (lambda x: 2*x)
add = lambda a, b: a+b
print(list(zip([1,2,3],[4,5,6])))
print(list(zipWith(add,[1,2,3],[4,5,6])))
"""

20
func/path.py Normal file
View File

@ -0,0 +1,20 @@
def path2FileName(path : "Path"):
return path.split("/")[-1]
def fname2Ext(fname):
return fname.split(".")[-1]
def fname2name(fname):
return "".join(fname.split(".")[:-1])

30
func/string.py Normal file
View File

@ -0,0 +1,30 @@
import re
def isMatch(rgx, s):
return bool(re.compile(rgx).match(s))
def strconcat(ls):
return "".join(ls)
def lines(s):
return s.split("\n")
def unlines(ls):
return "\n".join(map(str,ls))
def lines(s):
return s.split("\n")
def split(sign, ls):
rs = []
curr = []
for x in ls:
if x==sign:
rs.append(curr)
curr = []
else:
curr.append(x)
rs.append(curr)
return rs