Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

purescript data as array of all possible data inhabitants

I got the following data type:

data Icon = IconCircle | IconSquare | IconStar

I need an array of all possible Icons?:

allPossible :: Array Icon
allPossible = [IconCircle, IconSquare, IconStar]

Is there a shortcut to create this array? e.g when there are 20 (or a lot more) possible Icons?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When not:

Is it possible to create a type for allPossible that forces all possible Icons to be included?

My goal is to force that this array is never incomplete.

>Solution :

Yes, there is!

You can derive Generic and then use GenericEnum in combination with GenericBottom to enumerate all constructors:

data Icon = IconCircle | IconSquare | IconStar
derive instance Generic Icon _

allPossible :: Array Icon
allPossible = unfoldr (\a -> Tuple a <$> genericSucc a) genericBottom

And you can even make this completely generic, so it would work for any type, not just for Icon:

allPossible :: forall a rep. 
  Generic a rep =>
  GenericEnum rep => 
  GenericBottom rep => 
  Array a
allPossible = unfoldr (\a -> Tuple a <$> genericSucc a) genericBottom

Of course, this will only work for types that are actually enums – i.e. every constructor is either parameterless or its parameters have instances of Enum. If the type is not an enum in this sense, this will fail to compile, complaining that it’s impossible to construct a GenericEnum instance.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading