繁体   English   中英

自动函程实例

[英]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

但是,由于我没有实现FooFunctor实例,我不能使用fmap

有没有办法免费获得Functor实例? 我有Haskell的编译器的零知识,但也许是足够聪明的知道, fmapFoo a被简单地套用(a -> b)Fooa

在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM