Multisplit: Difference between revisions

m
Line 1,623:
def multiSplit(separators):
'''List of triples:
[(token, separator, start index of separator in string)].
'''
def go(s):
Line 1,631:
inDelim = offset > i
return maybe(
(tokens if inDelim else c + tokens, parts, offset)
tokens if inDelim
else c + tokens, parts, offset
where m is Just(x ).
)(
lambda x: ('', [(tokens, x, i)] + parts, i + len(x))
'',
[(tokens, x, i)] + parts,
i + len(x)
)
)(
Nothing()None if inDelim else find(
s[i:].startswith
)(separators)
Line 1,644 ⟶ 1,651:
 
 
# -------------------------- TEST-- -------------------------
# main :: IO ()
def main():
Line 1,655 ⟶ 1,662:
 
 
# -------------------- GENERIC FUNCTIONS- -------------------
 
# Justfind :: (a -> MaybeBool) -> [a] -> (a | None)
def Just(x):
'''Constructor for an inhabited Maybe (option type) value.
Wrapper containing the result of a computation.
'''
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
 
 
# Nothing :: Maybe a
def Nothing():
'''Constructor for an empty Maybe (option type) value.
Empty wrapper returned where a computation is not possible.
'''
return {'type': 'Maybe', 'Nothing': True}
 
 
# find :: (a -> Bool) -> [a] -> Maybe a
def find(p):
'''Just the first element in the list that matches p,
or NothingNone if no elements match.
'''
def go(xs):
for x in xstry:
return next(x for x in xs if p(x):)
except return Just(x)StopIteration:
return Nothing()None
return lambda xs: go(xs)
 
 
# maybe :: b -> (a -> b) -> Maybe (a | None) -> b
def maybe(v):
'''Either the default value v, if m is NothingNone,
or the application of f to x,.
where m is Just(x).
'''
return lambda f: lambda m: v if (
None is m or m.get('Nothing')
) else f(m.get('Just'))
 
 
9,659

edits