本文介绍了make的GADT(Haskell)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于GADT,是否有等价的 makeLenses ?如果我有一个简单的 GADT ,例如:

  data D ab其中
D ::(Ord a,Ord b)=> !a - > !b - > D ab

有没有办法通过传入构造函数和字段名称列表来自动生成镜头?我不认为这可以自动完成,但手动书写一些镜头并不难特殊情况:

  { - #LANGUAGE GADTs# - } 

导入Control.Lens

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

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

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

{ - 如果您想要改变类型的镜片,您也可以使用这些签名。
- 请注意,目标类型Ord约束必须转义。

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

成为一个有点相关的,其中Kmett声称他们无法制作镜片以进行存在量化字段。


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?

解决方案

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.

这篇关于make的GADT(Haskell)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 21:52