gpt4 book ai didi

haskell - 使用记录访问器定义 Applicative 的 <*> 时出错 : cannot construct the infinite type: t ~ t -> t1

转载 作者:行者123 更新时间:2023-12-02 16:45:53 26 4
gpt4 key购买 nike

我有以下代码:

{-# LANGUAGE DeriveFunctor #-}

data Foo a = Foo { field1 :: a, field2 :: a} deriving (Functor)

instance Applicative Foo where
pure a = Foo a a
f <*> a = Foo (r field1) (r field2)
where r g = g f $ g a

我在 GHCi 中收到以下错误:

help.hs:8:23: error:
• Occurs check: cannot construct the infinite type: t ~ t -> t1
• In the second argument of ‘($)’, namely ‘g a’
In the expression: g f $ g a
In an equation for ‘r’: r g = g f $ g a
• Relevant bindings include
g :: Foo (a -> b) -> t -> t1 (bound at help.hs:8:13)
r :: (Foo (a -> b) -> t -> t1) -> t1 (bound at help.hs:8:11)

help.hs:8:25: error:
• Couldn't match type ‘a’ with ‘a -> b’
‘a’ is a rigid type variable bound by
the type signature for:
(<*>) :: forall a b. Foo (a -> b) -> Foo a -> Foo b
at help.hs:7:5
Expected type: Foo (a -> b)
Actual type: Foo a
• In the first argument of ‘g’, namely ‘a’
In the second argument of ‘($)’, namely ‘g a’
In the expression: g f $ g a
• Relevant bindings include
g :: Foo (a -> b) -> t -> t1 (bound at help.hs:8:13)
r :: (Foo (a -> b) -> t -> t1) -> t1 (bound at help.hs:8:11)
a :: Foo a (bound at help.hs:7:9)
f :: Foo (a -> b) (bound at help.hs:7:3)
(<*>) :: Foo (a -> b) -> Foo a -> Foo b (bound at help.hs:7:3)

如何实现 Foo 的这个应用仿函数实例以便它可以编译?

最佳答案

定义

r g = g f $ g a

要求g是一个多态函数——GHC无法推断出如此复杂的类型。

如果您确实希望代码能够编译,则需要更明确地指定类型:

{-# LANGUAGE ScopedTypeVariables, DeriveFunctor, InstanceSigs, Rank2Types #-}
instance Applicative Foo where
pure a = Foo a a
(<*>) :: forall a b. Foo (a->b) -> Foo a -> Foo b
f <*> a = Foo (r field1) (r field2)
where
r :: (forall t. Foo t -> t) -> b
r g = g f $ g a

或者,可以使用一种更直接的方法:

instance Applicative Foo where
pure a = Foo a a
(Foo f1 f2) <*> (Foo a1 a2) = Foo (f1 a1) (f2 a2)

关于haskell - 使用记录访问器定义 Applicative 的 <*> 时出错 : cannot construct the infinite type: t ~ t -> t1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42424530/

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