-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs: Expand documentation structure
- Loading branch information
1 parent
ef7cee6
commit 88656b6
Showing
10 changed files
with
143 additions
and
130 deletions.
There are no files selected for viewing
This file contains 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
File renamed without changes.
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
# Создание Future используя Future CE | ||
|
||
Future имеет свой CE, который используется также как async или task CE встроенные в F#. | ||
Более подробно о CE вы можете прочитать на [сайте](https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/computation-expressions). | ||
|
||
Например, мы можем заменить базовые функции создания на future CE: | ||
```fsharp | ||
let ready = future { return "Hello, world!" } // ~ Future.ready "Hello, world!" | ||
let lazy' = future { return (foo ()) } // ~ Future.lazy' (fun () -> foo ()) | ||
``` | ||
|
||
Наиболее важным свойством CE является упрощение работы с bind. | ||
Пример чтения-записи можно переписать используя CE так: | ||
|
||
```fsharp | ||
// readFileAsync: filePath: string -> Future<string> | ||
// writeFileAsync: filePath: string -> content: string -> Future<unit> | ||
let readAndWriteFuture = futur { | ||
let! content = readFileAsync "my-file.txt" | ||
return! writeFileAsync "other-file.txt" content | ||
} | ||
``` | ||
|
||
Видимым преимуществом CE является возможность "уплощить" цепочка bind, зависимых между собой. | ||
Пример множественно зависимых bind можно переписать так: | ||
|
||
```fsharp | ||
let doManyWorkWithCrossResults = future { | ||
let! val1 = doWork1 () | ||
let! val2 = doWork2 val1 | ||
let! val3 = doWork3 val1 val2 | ||
... | ||
let! valN = doWorkN val1 val2 ... valPrevN | ||
} | ||
``` | ||
|
||
Также CE добавляют синтаксис и для Future.merge или Future.catch комбинаторов. | ||
|
||
```fsharp | ||
let parallelCE = future { | ||
let! val1 = doWork1 () | ||
and! val2 = doWork2 () | ||
and! val3 = doWork3 () | ||
} | ||
``` | ||
|
||
```fsharp | ||
let catchCE = future { | ||
try | ||
do! doWork () | ||
with ex -> | ||
printfn $"{ex}" | ||
} | ||
``` | ||
|
||
```fsharp | ||
let tryFinally = future { | ||
try | ||
do! doWork () | ||
finally | ||
do finallize () | ||
} | ||
``` |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
# Создание Future ручной реализацией Future | ||
|
||
Future это всего-лишь интерфейс с методами Poll и Drop. | ||
Можно создать свою Future просто реализовав их. | ||
|
||
Ручная реализация Future корректным образом не такая тривиальная задача, | ||
требующая ручной реализации конечного или не очень автомата. | ||
Поэтому не рекомендуется делать это, только если Вы не разрабатываете | ||
API для использования механизма асинхронности на низком уровне. | ||
|
||
Объяснения и более подробные примеры следует искать в более продвинутых главах. | ||
|
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
# Создание Future из Async и Task | ||
|
||
Существующие Async и Task можно преобразовать в Future и использовать результат их работы. | ||
Исходные Async и Task будут запущены на своих родных системах запуска, но их результат будет | ||
передан через возвращенную Future. | ||
|
||
```fsharp | ||
let asyncToFuture = Future.ofAsync (async { ... }) | ||
let taskToFuture = Future.ofTask (task { ... }) | ||
``` | ||
|
||
Возможны и обратные преобразования. При этом Future будут запущены на механизме запуска | ||
соответствующего примитива при запуске этого примитива. | ||
|
||
```fsharp | ||
let futureToAsync = Future.ofAsync (async { ... }) | ||
let futureToTask = Future.ofTask (task { ... }) | ||
``` | ||
|
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
# Создание Future |
22 changes: 1 addition & 21 deletions
22
docs/ru/basics/running.md → docs/ru/basics/running/running-runtime.md
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
# Запуск Future без среды исполнения на текущем потоке | ||
|
||
Future можно запустить на текущем потоке используя `Future.runBlocking`. | ||
Переданная Future запустится, а вызывающий поток будет заблокирован | ||
пока не получится результат. | ||
```fsharp | ||
let fut = future { | ||
let! name = Future.ready "Alex" | ||
do! Future.sleepMs 1000 | ||
return $"Hello, {name}!" | ||
} | ||
let phrase = fut |> Future.runBlocking | ||
printfn $"{phrase}" | ||
``` |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
# Запуск Future |