Skip to content

Instantly share code, notes, and snippets.

@chiller
Last active May 22, 2018 14:55
Show Gist options
  • Save chiller/6b925742e5fc477cddabfd2deacb4fb7 to your computer and use it in GitHub Desktop.
Save chiller/6b925742e5fc477cddabfd2deacb4fb7 to your computer and use it in GitHub Desktop.
Sierpinski Triangle

How to run:

ghc fractal.hs
./fractal

TODO:

  • x y to row col
----- constants
sizev = 44
sizeh = 51
r = sin(pi / 3)
----- primitive shape constructors
type Shape = Float -> Float -> Bool
rect :: Shape
rect = \ x y -> x > 0
&& y > 0
&& x < sizev
&& y < sizeh
triangle :: Shape
triangle = \x y -> rect x y
&& r >= x / (2 * y)
&& r >= x / (2 * (sizeh - y))
----- operations on primitives
scale :: Float -> Shape -> Shape
scale by shape = \x y -> shape (x / by) (y / by)
move :: Float -> Float -> Shape -> Shape
move dx dy shape = \x y -> shape (x - dx) (y - dy)
(|+|) :: Shape -> Shape -> Shape
(|+|) s1 s2 = \x y -> s1 x y || s2 x y
----- shape transformers
triple :: Shape -> Shape
triple shape = scale 0.5 $
shape
|+| move 0 sizeh shape
|+| move (sizeh * r) (sizeh / 2) shape
shape = triple $ triple $ triple triangle
----- rendering
putPixel shape row col = putStr $ if (shape row col) then "█ " else ". "
putRow row = putChar '\n' >> mapM_ (putPixel shape row) [1..sizeh]
main = mapM_ putRow [1..sizev]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment