Created
August 31, 2025 15:23
-
-
Save altbodhi/a767902980f82887add762d9e34016e0 to your computer and use it in GitHub Desktop.
F# Continuation Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // продолжения на F# | |
| type Cont<'a, 'r> = ('a -> 'r) -> 'r | |
| module Cont = | |
| // Создание continuation из значения | |
| let ret (x: 'a) : Cont<'a, 'r> = | |
| fun k -> k x | |
| // Связывание continuation | |
| let bind (m: Cont<'a, 'r>) (f: 'a -> Cont<'b, 'r>) : Cont<'b, 'r> = | |
| fun k -> m (fun x -> f x k) | |
| // Запуск continuation | |
| let run (m: Cont<'a, 'a>) : 'a = | |
| m id | |
| // Computation expression для более удобной работы | |
| type ContBuilder() = | |
| member this.Return(x) = Cont.ret x | |
| member this.ReturnFrom m = m | |
| member this.Bind(m, f) = Cont.bind m f | |
| member this.Zero() = Cont.ret () | |
| let cont = ContBuilder() | |
| // Простой пример | |
| let example1() = | |
| let computation = | |
| cont { | |
| let! x = Cont.ret 5 | |
| let! y = Cont.ret 10 | |
| return x + y | |
| } | |
| printfn "%d" (Cont.run computation) // Выведет 15 | |
| example1 () | |
| // Пример с callCC (call-with-current-continuation) | |
| let callCC (f: ('a -> Cont<'b, 'r>) -> Cont<'a, 'r>) : Cont<'a, 'r> = | |
| fun k -> | |
| f (fun x -> | |
| fun _ -> k x) k | |
| // Демонстрация прерывания вычисления | |
| let exampleWithExit() = | |
| let computation = | |
| cont { | |
| let! x = Cont.ret 10 | |
| let! result = | |
| callCC (fun ret -> | |
| cont { | |
| let! y = Cont.ret 20 | |
| do! ret 100 // Досрочный выход | |
| return y | |
| } | |
| ) | |
| return result | |
| } | |
| printfn "%d" (Cont.run computation) // Выведет 100 | |
| exampleWithExit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment