我可以在makeLenses
具有约束的数据类型上使用模板吗?如果可以,如何使用?我想这样做而不阅读有关Template 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
and makeClassy
,无济于事。
我知道我可以解决这个问题:
field1 :: (Class1 a) => Lens' (Foo a) a
field1 = lens _field1 (\ foo val -> Foo { _field1 = val })
但是有没有办法使用makeLenses
或 Template Haskell 来做到这一点?
我正在使用 GHC 7.8.4lens
版和 4.8 版。
(注意:我知道关于 makeLenses 有类似的问题,但我仍然无法让它工作。我是 haskell 的初学者。)