Jump to content

Teacup rim text: Difference between revisions

→‎Functional Python: Refactored in terms of `until`, as in JS
(→‎{{header|JavaScript}}: Added a JS draft)
(→‎Functional Python: Refactored in terms of `until`, as in JS)
Line 700:
=={{header|Python}}==
===Functional===
Composing generic functions, avoiding premature optimisation (an unfused composition returns a value in less than a second here), and taking only circular words of more than two characters.
{{Trans|HaskellJavaScript}}
<lang python>'''Teacup rim text'''
 
from itertools import cycle, islice
from os.path import expanduser
 
Line 735 ⟶ 734:
are found in the lexicon.
'''
def go(sw):
returniLast 2 <= len(sw) and- all(map(1
lambda x: x in lexicon,
rotations(s)
))
return lambda w: go(w)
 
def gop(xstpl):
drop(lngi, -bln, n_)( = tpl
return xs[n:]iLast < i or (not bln)
 
def f(tpl):
# rotations :: String -> [String]
(i, _, x) = cycle(xs)tpl
def rotations(xs):
lambdareturn x:(1 + i, x in lexicon, rotated(x))
'''All rotations of xs.'''
return [
''.join(rotated(i)(xs))
for i in range(0, len(xs))
]
 
return 1 < iLast and until(p)(f)(
rotations(s0, True, w)
))[1]
 
return lambda ws: go(ws)
# GENERIC -------------------------------------------------
 
# drop :: Int -> [a] -> [a]
# drop :: Int -> String -> String
def drop(n):
'''The sublist of xs beginning at
(zero-based) index n.
'''
def go(xs):
if isinstance(xs, (list, tuple, str)):
return xs[n:]
else:
take(n)(xs)
return xs
return lambda xs: go(xs)
 
# GENERIC -------------------------------------------------
 
# lines :: String -> [String]
Line 787 ⟶ 772:
 
 
# rotated :: IntString -> [a] -> [a]String
def rotated(ns):
'''A list rotated n elements to the right.'''
return lambda xss[1:] + (s[0]
(lambda lng=len(xs): take(lng)(
drop(lng - n)(
cycle(xs)
)
))()
)
 
 
# takeuntil :: Int(a -> Bool) -> (a -> a) -> [a] -> [a]
def dropuntil(np):
# take :: Int -> String -> String
'''The result of repeatedly applying f until p holds.
def take(n):
The initial seed value is x.
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
returndef lambdago(f, xsx): (
xs[0:n]v = x
ifwhile isinstance(xs,not p(list, tuple)v):
else list(islice(xs, n) v = f(v)
) return v
return lambda xsf: lambda x: go(xsf, x)
 
 
9,659

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.