gpt4 book ai didi

Haskell:映射 runST

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

我有一个类型 [ST s (Int, [Int])] 的绑定(bind)我正在尝试申请runST使用映射到每个元素,如下所示:

name :: [ST s (Int, [Int])] --Of Course there is a real value here
map runST name

这给了我一条错误消息
Couldn't match expected type `forall s. ST s b0'
with actual type `ST s0 (Int, [Int])'
Expected type: [forall s. ST s b0]
Actual type: [ST s0 (Int, [Int])]
In the second argument of `map', namely `name'
In the expression: map runST name

我一定有什么误解。我知道 runST and function composition ,但不确定这是否适用。

感谢大家的时间!

最佳答案

每次使用 runST 运行状态转换器时,它在与所有其他状态转换器分开的某个本地状态上运行。 runST创建一个新的状态类型并使用该类型调用其参数。因此,例如,如果您执行

let x = runST (return ())
y = runST (return ())
in (x, y)

然后是第一个 return ()第二个 return ()将有不同的类型: ST s1 ()ST s2 () , 对于一些未知类型 s1s2runST 创建的.

您正在尝试调用 runST带有状态类型为 s 的参数.这不是 runST 的状态类型。创建,也不是您可以选择的任何其他类型。调用 runST ,您必须传递一个可以具有任何状态类型的参数。这是一个例子:
r1 :: forall s. ST s ()
r1 = return ()

因为 r1是多态的,它的状态可以有任何类型,包括 runST选择的任何类型.您可以映射 runST在多态列表 r1 s (与 -XImpredicativeTypes ):
map runST ([r1, r1] :: [forall t. ST t ()])

但是,您不能映射 runST在非多态列表上 r1 s。
map runST ([r1, r1] :: forall t. [ST t ()]) -- Not polymorphic enough

类型 forall t. [ST t ()]表示所有列表元素的状态类型为 t .但是它们都需要有独立的状态类型,因为 runST被每个人调用。这就是错误消息的含义。

如果可以为所有列表元素赋予相同的状态,那么您可以调用 runST一次如下图。不需要显式类型签名。
runST (sequence ([r1, r1] :: forall t. [ST t ()]))

关于Haskell:映射 runST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11662696/

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