The following code doesn\'t compile:
{-# LANGUAGE TemplateHaskell #-}
import Control.Lens
data MyType = MyType Int
data Outer = Outer { _inners :: [ Inner ] }
Because ix n
can fail (ex: n >= length list
) you need a clean way to fail. The clean failure of choice is the mempty
element from Monoid
. So the question that immediately arises is if your type can't be a Monoid then how would you like this code to fail?
I suggest you use ^?
instead of ^.
, thereby reusing the Monoid
named Maybe
:
*Main> o ^? inners . ix 2 . val
Nothing
*Main> o ^? inners . ix 0 . val
Just (MyType 1)