Koch Snowflake Implementation in Haskell

Tag: haskell Author: p99p99 Date: 2009-11-04

I was looking at this on the Wikipedia Page and was wondering if anyone has a working implementation of this.

I'm trying to learn Haskell, finding it slightly difficult and am working on the Koch Snowflake and Sierpinski Triangle.

Any code or suggestions welcome.


Best Answer

  1. Calculate the points of a triangle centered in the plane.
  2. At each point of the triangle, calculate the points of a triangle one-third its size, and the other way up (flipped along its horizontal middle).
  3. Pass each triangle to step 2, pass the results of that again to step 2, and so on.
  4. Do all that again, upside down.

That should give you a list of (lists of) triangles. Now draw these triangles on the screen to the depth that you think is reasonable.

Other Answer1

For these kind of pictures which have a lot of structure and are scale independent, I would recommend the diagrams package ( http://projects.haskell.org/diagrams/ ), it's really quite a fantastic piece of code, see the following code to generate Koch snowflake written by yours truly in a matter of minutes :

snowflake :: Int -> Trail R2
snowflake n = k <> k # rotateBy (-1/3) <> k # rotateBy (1/3)
  where k = koch n

koch :: Int -> Trail R2
koch 0 = P (-1,0) ~~ P (1,0)
koch n = k <> k # rotateBy (1/6) <> k # rotateBy (-1/6) <> k
  where k = koch (n-1) # scale (1/3)

Which is almost self-explanatory, most of the magic is in the Monoid instance of Trail which will "concatenate" the trails end to end.

Note : (<>) is an operator for mappend, diagrams defined it in the past but this is now part of base in GHC 7.4 and will probably be included in a future version of the Haskell report, (#) is just the application reversed because diagrams author found it more pleasant to define a diagram then apply its attribute rather than write it in the other direction (so k # rotateBy (1/6) is just rotateBy (1/6) k).

Other Answer2

For sierpinski's triangle you can look here: click me

You may also find this helpful: http://www.hardforum.com/showthread.php?p=1034927217

And here is a suggestion that may also help: http://www.rhinocerus.net/forum/lang-functional/96046-haskell-fractals-specifically-snowflakes.html