gpt4 book ai didi

haskell - 构造延续类型?

转载 作者:行者123 更新时间:2023-12-04 15:31:05 24 4
gpt4 key购买 nike

我正在讨论延续,我遇到了两种构建延续类型的不同方法:

newtype C r a = C {runC :: (a -> r) -> r}

exampleFunction :: String -> C Bool String
exampleFunction s = C $ \t -> if length s > 10 then t s else False

continuationFunction :: String -> Bool
continuationFunction s = True

main = do
let suspendedFunc = exampleFunction "testing"
let completedFunc = runC suspendedFunc $ continuationFunction

Poor Mans Concurrency 中采用的方法相比:
type C r a = (a -> r) -> r

exampleFunction :: String -> C Bool String
exampleFunction s = \t -> if length s > 10 then t s else False

...

我知道后一种方法不使用显式数据构造函数。
  • 这些方法的实际区别是什么?
  • 当我尝试在带有 monad 的通用类型上使用它时,这会产生影响吗?如:
    data Hole = Hole1 Int | Hole2 String

    type C r m a = (a -> m r) -> m r

    exampleFunction :: String -> C Bool Maybe Hole
    exampleFunction s = \t -> do
    x <- t (Hole1 11)
    y <- t (Hole2 "test")
    ...

    continuationFunction :: Hole -> Bool
    continuationFunction (Hole1 x) = False
    continuationFunction (Hole2 y) = True
  • 最佳答案

    这些差异是 type 之间的常见差异。和 newtype .

    一个 type同义词只是现有类型的新名称。 type不能部分应用同义词,因为编译器会在类型检查期间扩展定义。例如,这不好,即使是 TypeSynonymInstances :

    type TypeCont r a = (a -> r) -> r

    instance Monad (TypeCont r) where -- "The type synonym ‘TypeCont’ should have 2 arguments, but has been given 1"
    return x = ($ x)
    k >>= f = \q -> k (\x -> (f x) q)
    newtype s 虽然在操作上等同于它们包装的类型,但在类型系统中是独立的实体。这意味着 newtype s 可以部分应用。
    newtype NewtypeCont r a = Cont { runCont :: (a -> r) -> r }

    instance Monad (NewtypeCont r) where
    return x = Cont ($ x)
    Cont k >>= f = Cont $ \q -> k (\x -> runCont (f x) q)

    关于haskell - 构造延续类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42293140/

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