Pernicious numbers: Difference between revisions

m
→‎Python :: Functional: Updated primitives.
m (Forth - simpler primality test)
m (→‎Python :: Functional: Updated primitives.)
Line 2,101:
'''
def go(x):
return Just(divmod(x, 2)) if 0 < x else Nothing()None
return sum(unfoldl(go)(n))
 
 
# TEST --------------------------- TEST -------------------------
# main :: IO ()
def main():
Line 2,111:
[888,888,877..888,888,888]
'''
 
print(
take(25)(
Line 2,123 ⟶ 2,124:
 
 
# GENERIC ------------------------- GENERIC ------------------------
 
# Just :: a -> Maybe a
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}
 
 
# enumFromTo :: Int -> Int -> [Int]
Line 2,145 ⟶ 2,130:
'''Enumeration of integer values [m..n]'''
def go(n):
return list(range(m, 1 + n))
return lambda n: go(n)
 
 
Line 2,182 ⟶ 2,167:
# unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
def unfoldl(f):
'''A lazy (generator) list unfolded from a seed value
'''Dual to reduce or foldl.
Whereby theserepeated reduceapplication aof listf tountil ano summaryresidue value, unfoldlremains.
buildsDual ato list from a seed valuefold/reduce.
Where f returns Just(a,either b),None aor isjust appended(residue, to the list,value).
andFor thea residualstrict boutput islist, used aswrap the argumentresult for thewith nextlist()
application of f.
When f returns Nothing, the completed list is returned.
'''
def go(v):
x, rresidueValue = f(v, v)
xswhile = []residueValue:
while True: yield residueValue[1]
mbresidueValue = f(xresidueValue[0])
return xsgo
if mb.get('Nothing'):
return xs
else:
x, r = mb.get('Just')
xs.insert(0, r)
return xs
return lambda x: go(x)
 
 
9,655

edits