makeLenses for GADTs (Haskell)

巧了我就是萌 提交于 2020-01-11 08:29:09

问题


Is there an equivalent of makeLenses for GADTs? If I have a simple GADT like:

data D a b where
  D :: (Ord a, Ord b) => !a -> !b -> D a b

Is there a way to generate lenses automatically by passing in a constructor and a list of field names?


回答1:


I don't think it can be done automatically, but writing some lenses by hand isn't that hard in this particular case:

{-# LANGUAGE GADTs #-}

import Control.Lens

data D a b where
  D :: (Ord a, Ord b) => !a -> !b -> D a b

field1 :: Lens' (D a b) a
field1 f (D x y) = fmap (\x' -> D x' y) (f x)

field2 :: Lens' (D a b) b
field2 f (D x y) = fmap (\y' -> D x y') (f y)

{- If you want type-changing lenses, you can also use these signatures.
 - Note that then the target type Ord constraint has to escape.

field1 :: (Ord a2) => Lens (D a1 b) (D a2 b) a1 a2
field2 :: (Ord b2) => Lens (D a b1) (D a b2) b1 b2
 -}

There seems to be a somewhat relevant GitHub issue, in which Kmett claims they cannot create lenses for existentially quantified fields.



来源:https://stackoverflow.com/questions/28145369/makelenses-for-gadts-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!