gpt4 book ai didi

haskell - 使 (a, a) 成为仿函数

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

如何制作 (a, a)一个 Functor不诉诸 newtype ?

基本上我希望它像这样工作:

instance Functor (a, a) where
fmap f (x, y) = (f x, f y)

但这当然不是表达它的合法方式:
Kind mis-match
The first argument of `Functor' should have kind `* -> *',
but `(a, a)' has kind `*'
In the instance declaration for `Functor (a, a)'

我真正想要的是这样的类型级函数: \a -> (a, a) (无效的语法)。所以一个类型别名,也许?
type V2 a = (a, a)
instance Functor V2 where
fmap f (x, y) = (f x, f y)

我认为这会起作用,但事实并非如此。首先,我收到此投诉:
Illegal instance declaration for `Functor V2'
(All instance types must be of the form (T t1 ... tn)
where T is not a synonym.
Use -XTypeSynonymInstances if you want to disable this.)
In the instance declaration for `Functor V2'

如果我按照建议添加 TypeSynonymInstances扩展,我收到一个新错误:
Type synonym `V2' should have 1 argument, but has been given 0
In the instance declaration for `Functor V2'

嗯,嗯,这就是重点! V2有样 * -> *这是 Functor 所需要的实例。好吧,我可以使用 newtype像这样:
newtype V2 a = V2 (a, a)
instance Functor V2 where
fmap f (V2 (x, y)) = V2 (f x, f y)

但现在我必须洒 V2 s 自由地贯穿我的代码,而不是仅仅能够处理简单的元组,这有点违背了将其设为 Functor 的意义。 ;到时候我还不如自己做函数 vmap :: (a -> b) -> (a, a) -> (b, b) .

那么有什么方法可以很好地做到这一点,即没有 newtype ?

最佳答案

正如其他人所说,如果不求助于新类型或数据声明,就无法做到这一点。然而,你看过Control.Arrow吗? ?其中许多函数对元组非常有用,例如:

vmap :: (a -> b) -> (a,a) -> (b,b)
vmap f = f *** f

关于haskell - 使 (a, a) 成为仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4812633/

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