[英]Automatic Functor Instance
给出以下代数类型:
ghci> data Foo a = Foo a
然后我实例化其中一个。
ghci> let f = Foo "foo"
最后,我想调用fmap
来应用函数, (a -> b) -> Foo a -> Foo b
。
ghci> fmap (++ "bar") f
<interactive>:78:1:
No instance for (Functor Foo) arising from a use of ‘fmap’
In the expression: fmap (++ "bar") f
In an equation for ‘it’: it = fmap (++ "bar") f
但是,由于我没有实现Foo
的Functor
实例,我不能使用fmap
。
有没有办法免费获得Functor
实例? 我有Haskell的编译器的零知识,但也许是足够聪明的知道, fmap
上Foo a
被简单地套用(a -> b)
到Foo
的a
?
在ghci工作,如果你做咒语
Prelude> :set -XDeriveFunctor
然后编译器将变得像你希望的那样聪明,如果不是那么热情。 您需要调用该功能,因此,
Prelude> data Foo a = Foo a deriving (Show, Functor)
( Show
只是用于打印输出,下面)然后你就可以做类似的事了
Prelude> fmap (++"bar") (Foo "foo")
Foo "foobar"
在模块中,您可以通过添加pragma来实现相同的功能
{-# LANGUAGE DeriveFunctor #-}
在module
声明之前。 这对于至少更简单的Functor
实例来说是好事,但是你可以把它Functor
假阴性。
Prelude> data Boo a = Boo (Either a Bool) deriving Functor
<interactive>:9:43:
Can't make a derived instance of ‘Functor Boo’:
Constructor ‘Boo’ must use the type variable only as the
last argument of a data type
In the data declaration for ‘Boo’
与此同时
data Goo a = Goo (Either Bool a) deriving Functor
没问题,机器显然已被黑客攻击配对,如
data Woo a = Woo (a, Bool) deriving Functor
是允许的。
所以它并不像它那样聪明,但它比眼中的捅更好。
当然可以,在数据声明中添加deriving Functor
,在文件顶部添加{-# LANGUAGE DeriveFunctor #-}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.