Harshad or Niven series: Difference between revisions

m
→‎Python: Functional: Updated primitives
(Add PL/M)
m (→‎Python: Functional: Updated primitives)
Line 3,239:
'''Sum of the decimal digits of n.'''
def go(x):
return Nothing()None if 0 == x else Just(divmod(x, 10))
return sum(unfoldl(go)(n))
 
 
# TEST --------------------------- TEST -------------------------
# main :: IO ()
def main():
Line 3,266:
 
 
# 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}
 
 
# take :: Int -> [a] -> [a]
Line 3,297 ⟶ 3,281:
 
 
# unfoldl(lambda x: Just(((x - 1), x)) if 0 != x else Nothing())(10)
# -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 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)
 
 
# DISPLAY ------------------------- DISPLAY ------------------------
 
# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function -> fx display function ->
fx display function -> f -> xs -> tabular string.
'''
def gogox(xShow, fxShow, f, xs):
ysdef = [xShowgofx(xfxShow) for x in xs]:
w = max(map(len, ys) def gof(f):
return s + '\n' + '\n'.join(map def goxs(xs):
lambda x, y: y.rjust(w, ' ') + ' ->ys '= + fxShow(f[xShow(x)), for x in xs]
xs w = max(map(len, ys))
 
))
x, r = mb.get def arrowed('Just'x, y):
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
return y.rjust(w, ' ') + ' -> ' + (
xShow, fxShow, f, xs
fxShow(f(x))
)
if mb.get('Nothing' ):
return s + '\n' + '\n'.join(
xs.insert map(0arrowed, xs, rys)
else: )
return xsgoxs
return gof
))return gofx
return lambda x: go(x)gox
 
 
Line 3,351 ⟶ 3,333:
# MAIN ---
if __name__ == '__main__':
main()</lang>
</lang>
{{Out}}
<pre>Harshad or Niven series:
9,659

edits