Trying out Diagrams

I’m trying out using Diagrams for including images in the web site. Let’s see if this works.

First diagram

The following is the first diagram I tried:

import Diagrams.Runner

main :: IO ()
main = putDiagram defaultOptions myCircle

myCircle :: Diagram B
myCircle = circle 1 # fc red

It is a circle filled with the color red in light mode. In dark mode, colors will be inverted.

First diagram

The code snippet above imports the Diagrams.Runner module, which is a custom module for this web site to generate SVG output from Diagrams. It exports the putDiagram function which does this work.

In subsequent code snippets, I will omit the import statement and the definition of the main function.

Combining diagrams

A circle atop another:

example :: Diagram B
example = circle 2 # lc purple `atop` circle 1 # lc green
Circle atop another

A circle and a square side by side:

example :: Diagram B
example = circle 1 ||| square 2
Circle and square side by side

A circle stacked on above a square:

example :: Diagram B
example = circle 1 === square 2
Circle above square

Three rows of growing circles:

circles :: Diagram B
circles = hcat $ map circle [1..6]

example :: Diagram B
example = vcat $ replicate 3 circles
Rows of growing circles

Aligning shapes

Circles of different sizes aligned on the top:

example :: Diagram B
example = hrule (2 * sum sizes) === circles # centerX
  where
    circles = hcat $ map (alignT . (`scale` circle 1)) sizes
    sizes = [2, 5, 4, 7, 1, 3]
Shapes aligned on top

Fractals

These diagrams are from the diagrams-contrib package.

A Koch snowflake:

import Diagrams.TwoD.Path.IteratedSubset

example :: Diagram B
example = strokeTrail $ snowflake 5
Koch snowflake

A Sierpinski triangle:

import Diagrams.TwoD.Path.LSystem

example :: Diagram B
example = getTurtleDiagram $ sierpinski 8
Sierpinski triangle

Tree figure generated with an L-system:

import Diagrams.TwoD.Path.LSystem

example :: Diagram B
example = rotateBy 0.25 $ getTurtleDiagram $ tree4 7
A tree

Conclusion

Yes, it works.

I am terrible at drawing images by hand. I don’t even want to draw anything by hand. So getting images declaratively generated by Diagrams whenever I need one is going to be a great help.

See also