3

I have a data type defined in another library. I would like to hook into that datatype with a lens generated by the Control.Lens library.

Do I need to newtype my type in my code or is it considered safe to lens an already defined data type?

TallerGhostWalt
  • 464
  • 3
  • 11
  • 2
    I would say it's safe to provide lenses (and other related things) for types that are already defined. In fact, the lens library does this (`[]`, `Maybe`, etc). – David Young Feb 17 '14 at 23:26
  • 6
    The only reason that it's not safe with instances is that instances are global and required to be unique. Lenses are neither global nor required to be the only one with their type. – Carl Feb 17 '14 at 23:29

1 Answers1

6

You don't need a newtype. There are actually many packages on hackage that define lenses for already existing types (for example, xml-lens or even lens itself).

The problem with defining instances is that there is no way to hide them. If you define lenses, you can just hide them when importing, like any other function:

import Module.Lens hiding (someGeneratedLens, ...)

This is not possible with instances (See https://stackoverflow.com/a/8731340/2494803 for reasons). Lenses are also not required to be globally unique, unlike instances.

Community
  • 1
  • 1
bennofs
  • 11,873
  • 1
  • 38
  • 62