One-dimensional cellular automata: Difference between revisions
m
→Python :: Composition of pure functions
(→Python :: Composition of pure functions: Tidied, updated primitives.) |
|||
Line 3,987:
return bool(intRule & 2**intFromBools([l, x, r]))
# go :: [Bool] -> [Bool]
def go(xs):
return [False] + list(map(
Line 3,999:
def intFromBools(xs):
'''Integer derived by binary interpretation
of a list of booleans.
'''
def go(b, pn):
power, n = pn
Line 4,009 ⟶ 4,010:
# main :: IO ()
def main():
'''Samples of Wolfram rule evolutions.
'''
print(
unlines(map(showRuleSample, [104, 30, 110]))
Line 4,020 ⟶ 4,021:
# showRuleSample :: Int -> String
def showRuleSample(intRule):
'''16 steps in the evolution
of a given Wolfram rule.
'''
return 'Rule ' + str(intRule) + ':\n' + (
unlines(map(
Line 4,038 ⟶ 4,041:
def boolsFromInt(n):
'''List of booleans derived by binary
decomposition of an integer.
'''
def go(x):
return Just((x // 2, bool(x % 2))) if x else Nothing()
Line 4,047 ⟶ 4,051:
def nBoolsFromInt(n):
'''List of bools, left-padded to given length n,
derived by binary decomposition of an integer x.
'''
def go(n, x):
bs = boolsFromInt(x)
Line 4,057 ⟶ 4,062:
def onePixelInLineOf(n):
'''A row of n (mainly False) booleans,
with a single True value in the middle.
'''
return nBoolsFromInt(n)(
2**(n // 2)
Line 4,065 ⟶ 4,071:
# randomPixelsInLineOf :: Int -> [Bool]
def randomPixelsInLineOf(n):
'''A row of n booleans with pseudorandom values.
'''
return [bool(randint(0, 1)) for _ in range(1, 1 + n)]
Line 4,071 ⟶ 4,078:
# showCells :: [Bool] -> String
def showCells(xs):
'''A block string representation of a list of booleans.
'''
return ''.join([chr(9608) if x else ' ' for x in xs])
Line 4,079 ⟶ 4,087:
# 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}
|