Middle three digits: Difference between revisions
Content deleted Content added
→{{header|Python}}: Added an illustration of using an option type in Python |
|||
Line 3,856:
# mid3digits :: Int -> Either String String
def mid3digits(n):
def go(s):
Line 3,884:
) for n in xs
]),
)
# GENERIC -------------------------------------------------
# either :: (a -> c) -> (b -> c) -> Either a b -> c
def either(fl):
return lambda fr: lambda e: fl(e['Left']) if (
None is e['Right']
) else fr(e['Right'])
# even :: Int -> Bool
def even(x):
return 0 == x % 2
# justifyRight :: Int -> Char -> String -> String
def justifyRight(n):
return lambda cFiller: lambda a: (
((n * cFiller) + str(a))[-n:]
)
# Left :: a -> Either a b
def Left(x):
return {'type': 'Either', 'Right': None, 'Left': x}
# maximumBy :: (a -> a -> a) -> [a] -> a
def maximumBy(f):
def go(x, y):
return y if f(y) > f(x) else x
return lambda xs: reduce(go, xs[1:], xs[0])
# Right :: b -> Either a b
def Right(x):
return {'type': 'Either', 'Left': None, 'Right': x}
if __name__ == '__main__':
main()</lang>
{{Out}}
<pre> 123 -> 123
|