Translation Scheme call / cc in Haskell callCC

Let's look at opening an otherwise non-ending fold:

(call/cc (lambda (folded) (stream-fold (lambda (acc v) (if (< v 5) (cons v acc) (folded acc))) '() (in-naturals 0)))) ; returns '(4 3 2 1 0) 

the Haskell equivalent for the above code would be

 callCC $ \folded -> foldl (\acc v -> if v < 5 then v:acc else folded acc) [] [0..] 

This code does not compile and does not complain about the inability to build an infinite type in the expression folded acc. I already have an idea how to fix this error in cases like Y combinator, but the same approach does not seem to work here. What is the right approach for this kind of situation?

+6
source share
2 answers

Yes; like j. Abrahamson says

 import Control.Monad.Trans.Cont import Control.Monad bar :: Cont r [Int] bar = callCC $ \folded -> foldM (\acc v -> do when (v >= 5) $ folded acc return $ v : acc) [] [0..] thing = runCont bar id 

work.

+6
source

First of all, calling Scheme / cc and Haskell callCC are slightly different things, as explained on the page unsupported continuations are not functions

The main problem is that you may not need call / cc at all - even on the Scheme. Your example of exiting the loop is much better implemented using exceptions - better in terms of efficiency (there is no need to fix a continuation that you will not use in any case), and better conceptually. If the task is to interrupt current continuations, there are tools for this purpose. The R7RS recognized this and introduced exceptions. To use exceptions in Haskell, use the error or any monad. For example, in your code

 baz :: Either [Int] [Int] baz = foldM (\acc v -> do when (v >= 5) $ Left acc return $ v : acc) [] [0..] thing1 = either id id baz 

The call / cc operator was introduced in the diagram when there is little experience with control operators. Now we have a lot of experience, and many serious flaws of call / cc came to light. If you are interested in more information, the next page details problems with call / cc. Argument against calling / cc

+1
source

Source: https://habr.com/ru/post/976921/


All Articles