我可以在带有约束的数据类型上使用makeLenses模板吗?如果可以,如何使用?我不想读任何关于模板Haskell的文章。
在GHC中,我有一个例子:
{-# 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 }这会产生以下编译错误:
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所以我认为它产生了:
field1 :: Lens' (Foo a) a我也尝试过makeFields和makeClassy,但没有结果。
我知道我可以处理这件事
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的初学者。)
发布于 2015-03-18 23:33:31
问题是,我相信,数据类型的上下文是一个有点支离破碎的特性。您可能打算使用GADT:
{-# Language GADTs #-}
data Foo a where
Foo :: Class1 a => a -> Foo a我不知道如何使用类约束在其中获得记录语法。
不幸的是,作为rjan Johansen 评论,您将立即遇到麻烦,自动制作的镜头,因为存在类型。但是,我相信,您应该能够手工编写它们,而数据类型上下文则永远不会起作用。
https://stackoverflow.com/questions/29134349
复制相似问题