Bab*_*ham 6 continuations haskell types newtype type-synonyms
我正在讨论延续,我遇到了两种不同的方法来构建延续类型:
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
Run Code Online (Sandbox Code Playgroud)
与穷人并发中的方法相比:
type C r a = (a -> r) -> r
exampleFunction :: String -> C Bool String
exampleFunction s = \t -> if length s > 10 then t s else False
...
Run Code Online (Sandbox Code Playgroud)
我知道后一种方法不使用显式数据构造函数.
当我尝试在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
Run Code Online (Sandbox Code Playgroud)差异是type和之间的常见差异newtype。
同义词type只是现有类型的新名称。type同义词不能部分应用,因为编译器在类型检查期间扩展了定义。例如,即使使用以下方法,这也不好TypeSynonymInstances:
type TypeCont r a = (a -> r) -> r\n\ninstance Monad (TypeCont r) where -- "The type synonym \xe2\x80\x98TypeCont\xe2\x80\x99 should have 2 arguments, but has been given 1"\n return x = ($ x)\n k >>= f = \\q -> k (\\x -> (f x) q)\nRun Code Online (Sandbox Code Playgroud)\n\nnewtypes 虽然在操作上等同于它们所包装的类型,但它们是类型系统中的独立实体。这意味着newtype可以部分应用。
newtype NewtypeCont r a = Cont { runCont :: (a -> r) -> r }\n\ninstance Monad (NewtypeCont r) where\n return x = Cont ($ x)\n Cont k >>= f = Cont $ \\q -> k (\\x -> runCont (f x) q)\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
93 次 |
| 最近记录: |