【问题标题】:How to use a Reader type encoded with continuation passing style如何使用以连续传递样式编码的 Reader 类型
【发布时间】:2018-02-08 18:12:11
【问题描述】:

我的印象是,a 类型的每个值都可以用 rank-2 多态类型 newtype Id a = Id {runId :: forall r. (a -> r) -> r } 以连续传递方式来描述。所以我派生了以下类型来相应地定义Reader

newtype Reader e a = Reader {runReader :: forall r. ((e -> a) -> r) -> r}

然后我尝试构造一个这种类型的值并运行它:

reader f = Reader (\k -> k f) -- where is f's argument?
runReader (reader id) -- what is the 2nd argument?

如果Reader在CPS中的编码及其类型是有效的,我该如何使用呢?

【问题讨论】:

    标签: haskell continuation-passing higher-rank-types scott-encoding


    【解决方案1】:
    reader f = Reader (\k -> k f) -- where is f's argument?
    

    我们现在不必传递第二个参数。这与不涉及第二个参数的常规 data Reader e a = Reader (e->a)reader f = Reader f 非常相似。

    runReader (reader id) -- what is the 2nd argument?
    

    一般方程是

    runReader (reader f) k = k f
    

    所以,

    runReader (reader f) id x = id f x = f x
    

    您可以使用f = id(在真正的阅读器monad 中的作用类似于ask),但不要将它与作为延续k 提供的另一个id 混淆,它恢复原始f.

    【讨论】:

    • 我想你想要id f x = f x,而不是id f x = x
    • 定义一个帮助器runReader' = flip runReader id 以摆脱延续可能很有用。
    猜你喜欢
    • 2012-09-17
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 2016-11-21
    • 2012-07-04
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    相关资源
    最近更新 更多