How to use Inspect.Algebra?

As some of you might now, I am creating a Multi User Dungeon (a text-based multiplayer game) in Elixir. This is mostly a hobby project, to learn what a non-trivial project in Elixir will look like, and do’s and don’t when an Elixir project grows in size.

The text that is generated in the game is sent over a simple TCP connection to the telnet shells of connected clients. What I would like to do, is to format this text, so lines break nicely, instead of cutting words in half.

I think the Inspect.Algebra module is useful for this, as I presume that this is what Elixir uses underwater to print the pretty-printed documentation whenever you use h Modulename in IEx.

However, I am a bit stumped on how to use it properly. Can someone explain how I can use it to generate line-breaks from an iodata string?

1 Like

I toyed with it once briefly, but I’m pretty sure the APIs have changed since then. The best example I know of is in the Programming Elixir book, and now that I review it, it’s not as extensive as I recall.

2 Likes

Inspect.Algebra is a set of tools for implementing the Inspect protocol for your data types.

Probably the best place to figure out how to use it is in the Elixir source code itself.

Look at the defimpl Inspect for the various data types to get examples.

3 Likes

BTW, digging through the code of Inspect is how I actually really understood protocols and I “borrowed” much of the structure of phst_transform from the Inspect protocol.

2 Likes