10 Oct 23:00 2013

## Conditional lens

Artyom Kazak <yom <at> artyom.me>

2013-10-10 21:00:44 GMT

2013-10-10 21:00:44 GMT

Hello! I am working with TypeReps, and while writing some functions I have noticed that I could use lenses to simplify them; however, I have stumbled upon some difficulties. First I’ll try to clarify which functions I want to write: * a function for converting TypeRep of, say, `Maybe x` to `[x]` (for all x). It requires checking if the TyCon is `Maybe` and replacing it with []-TyCon. If it wasn’t `Maybe`, I return Nothing. * a similar function for replacing `Char`s and `Lazy.Text`s to just `Text`. Again, if the TypeRep-to-be-replaced doesn’t satisfy my conditions, I return Nothing. These two functions (and some others, I suppose) can be written concisely with the help of one combinator. I don’t know how to write it as a composable Lens, so I’ll give it here as an ad-hoc Lens-modifying function instead: ifL :: (a -> Bool) -> Lens s t a b -> Lens s (Maybe t) (Maybe a) b ifL p l = lens getter setter where get s = getConst $ l Const s getter s = let a = get s in if p a then Just a else Nothing setter s b = let a = get s in if p a then Just (set l b s) else Nothing(Continue reading)