Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a new Set monoid #57

Closed
wants to merge 2 commits into from
Closed

Conversation

BlackCapCoder
Copy link
Contributor

@BlackCapCoder BlackCapCoder commented Oct 24, 2024

Here's a Monoid I've re-implemented a bunch of times, and I thought it might fit in here!

My use-case is when you have some sort of Config datatype:

data Config = Config
  { foo, bar, baz :: Set Bool
  , ...
  }

unit = Config Unset Unset Unset

Unlike maybe, we can specify only some of the fields of our datatype and combine them with (<>) without inadvertently clearing all the stuff we left out

ex0 = unit { foo = Clear }
ex1 = unit { bar = Set True }
ex2 = unit { baz = Set False }

ex3 = ex0 <> ex1 <> ex2

For a real world example, consider rendering in an ANSI terminal. Each "pixel" can have a bunch of styling (Bold, Blink, Underline, Foreground and background color, an actual character..). Set let us do the rendering in parts by composing a bunch of Array Pixels together. Clear let us only remove- say- the background color, but leave everything else as-is, and an explicit clear means that we have to update the terminal, unlike Unset.

Set a is equivalent to Maybe (Data.Semigroup.Last (Maybe a)), but exactly nobody is going to use that over just re-implementing Set for the fifteenth time!

@BlackCapCoder
Copy link
Contributor Author

BlackCapCoder commented Oct 25, 2024

https://hackage.haskell.org/package/focus-1.0.3.2/docs/Focus.html#t:Change

I actually looked for this library prior to posting, but I couldn't remember the name!

@byorgey
Copy link
Member

byorgey commented Oct 25, 2024

Thanks for the PR! I've actually re-implemented something similar to this myself, in https://github.com/swarm-game/swarm/blob/main/src/swarm-util/Swarm/Util/Erasable.hs (except in that version 'set' values are combined with an underlying Semigroup rather than having Last be built-in). So it's nice to know the version in focus exists, I didn't know about that before.

I think this could actually make a nice addition to monoid-extras except I definitely wouldn't want to name it Set because that naming conflicts with Data.Set (yes, you can use qualified imports, but it's just confusing).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants