b) ->-6ren">
gpt4 book ai didi

haskell - 自动仿函数实例

转载 作者:行者123 更新时间:2023-12-01 07:25:50 26 4
gpt4 key购买 nike

给定以下代数类型:

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

但是,由于我没有实现 Functor Foo 的实例, 我不能使用 fmap .

有没有办法得到 Functor免费实例?我对 Haskell 的编译器的了解为零,但知道 fmap 可能已经足够聪明了。在 Foo 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 来说是有好处的实例,但您可以将其欺骗为假阴性。
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

是允许的。

所以它并不像它可能的那样聪明,但它总比戳眼睛好。

关于haskell - 自动仿函数实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28395214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com