indexing list with Control.Lens requires Monoid constraint

前端 未结 1 1213
误落风尘
误落风尘 2021-02-15 15:12

The following code doesn\'t compile:

{-# LANGUAGE TemplateHaskell #-}

import Control.Lens

data MyType = MyType Int
data Outer = Outer { _inners :: [ Inner ] }
         


        
1条回答
  •  醉梦人生
    2021-02-15 15:25

    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)
    

    0 讨论(0)
提交回复
热议问题