GADT的makeLenses(Haskell)

时间:2015-01-26 05:59:16

标签: haskell gadt lenses

GADT是否等同于makeLenses?如果我有一个简单的GADT喜欢:

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

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

1 个答案:

答案 0 :(得分: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 issue,其中Kmett声称他们无法为存在量化的领域创建镜头。