【发布时间】:2017-07-06 16:43:42
【问题描述】:
我正在讨论延续,我遇到了两种构建延续类型的不同方法:
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同义词只是现有类型的新名称;它们不能被部分应用,你不能让它们成为一个类的instance。newtypes 与它们包装的类型是分开的,您可以使用它们来编写自定义instances。例如,您将无法为type C编写Monad的实例。 -
谢谢@BenjaminHodgson - 你想回答我会接受吗?
标签: haskell types continuations newtype type-synonyms