gpt4 book ai didi

pointers - 为什么带有多态 Ptr 的 `peek` 在与绑定(bind)一起使用时会返回 GHC.Prim.Any?

转载 作者:行者123 更新时间:2023-12-03 06:32:42 26 4
gpt4 key购买 nike

使用low-level GNU Science Library bindings Bindings.Gsl.RandomNumberGeneration ,我在 GHCi 中遇到了这种奇怪的类型行为,其中绑定(bind)将返回类型从 peek 更改为 GHC.Prim.Any。我试图理解为什么,因为除非保留指向 rng 的指针类型,否则我无法使用 c'rng_alloc 。例如:

λ> :t c'gsl_rng_alloc
c'gsl_rng_alloc :: Ptr C'gsl_rng_type -> IO (Ptr C'gsl_rng)
λ> :t p'gsl_rng_mt19937
p'gsl_rng_mt19937 :: Ptr (Ptr gsl_rng_type)
λ> :t peek p'gsl_rng_mt19937
peek p'gsl_rng_mt19937 :: IO (Ptr gsl_rng_type)
λ> x <- peek p'gsl_rng_mt19937
λ> :t x
x :: Ptr GHC.Prim.Any
λ> c'gsl_rng_alloc x

<interactive>:421:17:
Couldn't match type ‘GHC.Prim.Any’ with ‘C'gsl_rng_type’
Expected type: Ptr C'gsl_rng_type
Actual type: Ptr GHC.Prim.Any
In the first argument of ‘c'gsl_rng_alloc’, namely ‘x’
In the expression: c'gsl_rng_alloc x
λ>

尝试显式指定 peek 返回的类型也没有帮助:

λ> x <- (peek p'gsl_rng_mt19937) :: IO (Ptr gsl_rng_type)
λ> :t x
x :: Ptr GHC.Prim.Any

最佳答案

对@user2407038的评论进行一些扩展:

When you do x <- peek (ptr :: Ptr (Ptr a)) in the GHCi prompt, the type variable a must be instantiated to some concrete type. This is because the do notation x <- peek p means peek p >>= \x -> ..., where ... is what you type into GHCi afterwards. Since GHCi can't know the future, it has to "cheat" during typechecking.

回想一下peek p >>= \x -> ...中的内容, >>= 的右侧参数,即 lambda 抽象 \x -> ... , is monomorphic in its argument 。这就是为什么 GHCi 必须将单态类型分配给 x

GHC.Prim.Any是 GHC 在需要将具体的单态类型分配给没有其他约束的事物的情况下使用的占位符类型。

关于pointers - 为什么带有多态 Ptr 的 `peek` 在与绑定(bind)一起使用时会返回 GHC.Prim.Any?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30036017/

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