Binary digits: Difference between revisions

→‎{{header|Python}}: Added a variant using a more general showIntAtBase function
(Add min)
(→‎{{header|Python}}: Added a variant using a more general showIntAtBase function)
Line 2,898:
 
=={{header|Python}}==
===String.format() method===
{{works with|Python|3.X and 2.6+}}
<lang python>>>> for i in range(16): print('{0:b}'.format(i))
Line 2,917 ⟶ 2,918:
1110
1111</lang>
 
===Built-in bin() function===
{{works with|Python|3.X and 2.6+}}
<lang python>>>> for i in range(16): print(bin(i))
Line 2,957 ⟶ 2,960:
1110
1111</lang>
 
===Custom functions===
 
Defined in terms of a more general '''showIntAtBase''' function:
<lang python>'''Binary strings for integers'''
 
 
# showBinary :: Int -> String
def showBinary(n):
'''Binary string representation of an integer.'''
def binaryChar(n):
return '1' if n != 0 else '0'
return showIntAtBase(2)(binaryChar)(n)('')
 
 
# TEST -------------------------------------------------
 
# main :: IO()
def main():
'''Test'''
 
print(unlines(
map(showBinary, enumFromTo(0)(16))
))
 
 
# GENERIC -------------------------------------------------
 
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
 
 
# showIntAtBase :: Int -> (Int -> String) -> Int -> String -> String
def showIntAtBase(base):
'''String representing a non-negative integer
using the base specified by the first argument,
and the character representation specified by the second.
The final argument is a (possibly empty) string to which
the numeric string will be prepended.'''
def wrap(toChr, n, rs):
def go(nd, r):
n, d = nd
r_ = toChr(d) + r
return go(divmod(n, base), r_) if 0 != n else r_
return 'unsupported base' if 1 >= base else (
'negative number' if 0 > n else (
go(divmod(n, base), rs))
)
return lambda toChr: lambda n: lambda rs: (
wrap(toChr, n, rs)
)
 
 
# unlines :: [String] -> String
def unlines(xs):
'''A single string derived by the intercalation
of a list of strings with the newline character.'''
return '\n'.join(xs)
 
 
if __name__ == '__main__':
main()</lang>
 
=={{header|Racket}}==
9,659

edits