F Sharp (programming language): Difference between revisions

Content deleted Content added
Shr2012 (talk | contribs)
Functional programming: Changed the emphasis to functional-first rather than supporting o-o features of C#.
Shr2012 (talk | contribs)
Asynchronous programming: Updated with task expressions.
Line 455:
 
The async block may be invoked using the <code>Async.RunSynchronously</code> function. Multiple async blocks can be executed in parallel using the <code>Async.Parallel</code> function that takes a list of <code>async</code> objects (in the example, <code>asynctask</code> is an async object) and creates another async object to run the tasks in the lists in parallel. The resultant object is invoked using <code>Async.RunSynchronously</code>.<ref name="aw">{{cite web |url=http://blogs.msdn.com/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx |title=Introducing F# Asynchronous Workflows |access-date=2007-12-14}}</ref>
 
[[Inversion of control]] in F# follows this pattern.<ref name="aw"/>
 
Since version 6.0, F# supports creating, consuming and returning .NET tasks directly. <ref>{{cite web |url=https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/task-expressions | title=Task Expressions|access-date=2023-01-15}}</ref>
 
<syntaxhighlight lang="fsharp">
open System.Net.Http
let fetchUrlAsync (url:string) = // string -> Task<string>
task {
let client = new HttpClient()
let! response = client.GetAsync(url)
let! content = response.Content.ReadAsStringAsync()
do! Task.Delay 500
return content
}
 
// Usage
let fetchPrint() =
let task = task {
let! data = fetchUrlAsync "https://example.com"
printfn $"{data}"
}
task.Wait()
 
</syntaxhighlight>
 
===Parallel programming===