Last active
August 29, 2015 14:13
-
-
Save maxdeliso/9ab01faff9450010aa0a to your computer and use it in GitHub Desktop.
Sierpinski.hs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sierpinski | |
a little program to generate sierpinski triangle patterns computed using a cellular automaton rule | |
takes two command line arguments: | |
the length of the initial string's outer run of 0s (total length is 2n+1) | |
the number of iterations | |
build it like this: | |
ghc Main.hs | |
run it like this: | |
./Main 10 10 | |
it should look like this: | |
"0000000000+0000000000" | |
"000000000+0+000000000" | |
"00000000+000+00000000" | |
"0000000+0+0+0+0000000" | |
"000000+0000000+000000" | |
"00000+0+00000+0+00000" | |
"0000+000+000+000+0000" | |
"000+0+0+0+0+0+0+0+000" | |
"00+000000000000000+00" | |
"0+0+0000000000000+0+0" | |
:) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main where | |
import System.Environment | |
import System.Exit | |
import Sierpinski | |
main = do args <- getArgs | |
if length args /= 2 then | |
error "two integer args required: width and iteration count" | |
else | |
let width = read (head args) :: Int | |
iterations = read (head $ tail args) :: Int | |
in if iterations < 0 then | |
error "iterations cannot be negative" | |
else printLoop (genCentered width) iterations | |
printLoop binSeq 0 = exitSuccess | |
printLoop binSeq n = do | |
print $ pretty binSeq | |
printLoop (step binSeq) (n - 1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Sierpinski(genCentered, pretty, step) where | |
-- generate a sequence of 2n+1 bits with a single centered True | |
genCentered n = let side = replicate n False in side ++ [True] ++ side | |
-- given a list of booleans, turn it into a nice sequence of printable chars | |
pretty xs = let pretty True = '+' | |
pretty False = '0' | |
in map pretty xs | |
-- toss out rightmost and prepend false | |
leftParents xs = False : init xs | |
-- toss out leftmost and append false | |
rightParents xs = tail xs ++ [False] | |
-- next generation is on if its diagonal parents differ, off otherwise | |
step xs = let left = leftParents xs | |
right = rightParents xs | |
diff (leftP, rightP) = leftP /= rightP | |
in zipWith (curry diff) left right |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment