Search code examples
haskellhaskell-lens

How to "compose" Iso's?


Here is my type:

newtype SaneDate = SaneDate UniversalTime
   deriving (Show, Eq, Typeable, Generic)
makeWrapped ''SaneDate

Now I need an iso with this type:

reprBuild :: Iso' (Maybe UniversalTime) (Fist SaneDate)

I did this:

reprBuild = iso
   (\ t -> First (SaneDate <$> t) )
   (\ sane_first -> fmap (^. _Wrapped) $ getFirst sane_first  )

But I have the impression I'm working extra-hard. Is there a (shorter) way of writing the reprBuild iso as a composition of things?


Solution

  • Recent versions of lens have that built in:

    reprBuild = coerced
    

    Of course, this requires safe coercions which are only available since 7.10; for backwards compatibility use a manual approach with mapping.