参见英文答案 >
runST and function composition 3个
我对以下程序感到困惑.
{-# LANGUAGE RankNTypes #-}
newtype A a = A ( forall f. Applicative f => f a )
good :: a -> A a
good x = A $pure $x
bad :: a -> A a
bad x = A . pure $x
在尝试编译时,我收到此错误消息,抱怨不好:
Couldn't match type `f0 a'
with `forall (f :: * -> *). Applicative f => f a'
Expected type: f0 a -> A a
Actual type: (forall (f :: * -> *). Applicative f => f a) -> A a
Relevant bindings include
x :: a (bound at huh.hs:8:6)
bad :: a -> A a (bound at huh.hs:8:1)
In the first argument of `(.)', namely `A'
In the expression: A . pure
为什么功能好的类型检查,而ghc拒绝接受功能不好?我能做些什么来使后一版本有效?据我所知,这两个例子应该是等价的.
最佳答案 正如在几条评论中所解释的那样,问题在于类型系统无法预测这是一种有效的类型,即使它是.在
this answer中有一个提示,您可以指定类型.明确地解决问题.
此代码段有效:
-- Type specialized composition
(.!) :: ((forall f. Applicative f => f b) -> c) ->
(a -> (forall f. Applicative f => f b)) -> a -> c
(.!) f g x = f(g x)
-- Use the new version of composition
notBad :: a -> A a
notBad x = A .! pure $x