Stern-Brocot sequence: Difference between revisions
→Python: Composing pure (curried) functions: Updated primitives.
Alextretyak (talk | contribs) (Added 11l) |
(→Python: Composing pure (curried) functions: Updated primitives.) |
||
Line 3,937:
<lang python>'''Stern-Brocot sequence'''
import math▼
from itertools import (count, dropwhile, islice, takewhile)▼
import operator
▲import math
Line 3,949:
def go(xs):
x = xs[1]
return (x, tail(xs) + [x + head(xs), x])
return
)▼
# TESTS ---------------------------------------------------▼
# main :: IO ()
def main():
Line 3,998 ⟶ 3,995:
#
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
Line 4,027 ⟶ 4,023:
'''True if p(x) holds for every x in xs'''
return lambda xs: all(map(p, xs))
# fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]▼
def fmapGen(f):▼
def go(g):▼
while True:▼
yield f(v)▼
return lambda gen: go(gen)▼
Line 4,053 ⟶ 4,035:
'''The first element of a non-empty list.'''
return xs[0]
v = x▼
Line 4,071 ⟶ 4,041:
'''A sublist of xs from which all duplicates,
(as defined by the equality predicate p)
are excluded.
def go(xs):
if not xs:
Line 4,082 ⟶ 4,053:
))
)
return
Line 4,100 ⟶ 4,071:
return xs[1:]
else:
return xs
Line 4,114 ⟶ 4,085:
else list(islice(xs, n))
)
'''A lazy (generator) list unfolded from a seed value
by repeated application of f until no residue remains.
Dual to fold/reduce.
f returns either None or just (value, residue).
For a strict output list, wrap the result with list()
'''
valueResidue = f(valueResidue[1])
|