首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带约束数据的makeLenses (DatatypeContexts)

带约束数据的makeLenses (DatatypeContexts)
EN

Stack Overflow用户
提问于 2015-03-18 23:07:30
回答 1查看 173关注 0票数 1

我可以在带有约束的数据类型上使用makeLenses模板吗?如果可以,如何使用?我不想读任何关于模板Haskell的文章。

在GHC中,我有一个例子:

代码语言:javascript
复制
{-# LANGUAGE TemplateHaskell, FlexibleInstances, UndecidableInstances, NoMonomorphismRestriction #-}
module Main (main) where

import Control.Lens
import Control.Monad.Reader  -- mtl

class Class1 a where
    someThing :: a  -- just some filler

instance (Num a) => Class1 a where
    someThing = 3

data (Class1 a) => Foo a = Foo { _field1 :: a }

makeLenses ''Foo

main :: IO ()
main = putStrLn . show $ runReader (view field1) $ Foo { _field1 = 5 }

这会产生以下编译错误:

代码语言:javascript
复制
Could not deduce (Num a1) arising from a use of ‘Foo’
from the context (Profunctor p, Functor f)
  bound by the type signature for
             field1 :: (Profunctor p, Functor f) =>
                       p a (f a1) -> p (Foo a) (f (Foo a1))
  at src/main.hs:58:1-16
Possible fix:
  add (Num a1) to the context of
    the type signature for
      field1 :: (Profunctor p, Functor f) =>
                p a (f a1) -> p (Foo a) (f (Foo a1))
In the second argument of ‘iso’, namely ‘Foo’
In the expression: iso (\ (Foo x_a3NK) -> x_a3NK) Foo
In an equation for ‘field1’:
    field1 = iso (\ (Foo x_a3NK) -> x_a3NK) Foo

所以我认为它产生了:

代码语言:javascript
复制
field1 :: Lens' (Foo a) a

我也尝试过makeFieldsmakeClassy,但没有结果。

我知道我可以处理这件事

代码语言:javascript
复制
field1 :: (Class1 a) => Lens' (Foo a) a
field1 = lens _field1 (\ foo val -> Foo { _field1 = val })

但是,有什么方法可以用makeLenses或模板Haskell来实现呢?

我使用的是GHC7.8.4版本和lens版本4.8。

(注:我知道关于makeLenses也有类似的问题,但我仍然无法让它发挥作用。我是haskell的初学者。)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-18 23:33:31

问题是,我相信,数据类型的上下文是一个有点支离破碎的特性。您可能打算使用GADT:

代码语言:javascript
复制
{-# Language GADTs #-}

data Foo a where
  Foo :: Class1 a => a -> Foo a

我不知道如何使用类约束在其中获得记录语法。

不幸的是,作为rjan Johansen 评论,您将立即遇到麻烦,自动制作的镜头,因为存在类型。但是,我相信,您应该能够手工编写它们,而数据类型上下文则永远不会起作用。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29134349

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档