8

是否有makeLensesGADT 的等价物?如果我有一个简单的GADT喜欢:

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

有没有办法通过传入构造函数和字段名称列表来自动生成镜头?

4

1 回答 1

7

我不认为它可以自动完成,但在这种特殊情况下,手动编写一些镜头并不难:

{-# 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
 -}

似乎有一个有点相关的GitHub 问题,其中 Kmett 声称他们无法为存在量化领域创建镜头。

于 2015-01-26T06:53:56.963 回答