簡體   English   中英

什么是F#的異步工作流的Scala等價物?

[英]What is the Scala equivalent of F#'s async workflows?

什么是F#的異步工作流的Scala等價物?

例如,如何跟隨F#snippet轉換為慣用的Scala?

open System.Net
open Microsoft.FSharp.Control.WebExtensions

let urlList = [ "Microsoft.com", "http://www.microsoft.com/"
                "MSDN", "http://msdn.microsoft.com/"
                "Bing", "http://www.bing.com"
              ]

let fetchAsync(name, url:string) =
    async { 
        try
            let uri = new System.Uri(url)
            let webClient = new WebClient()
            let! html = webClient.AsyncDownloadString(uri)
            printfn "Read %d characters for %s" html.Length name
        with
            | ex -> printfn "%s" (ex.Message);
    }

let runAll() =
    urlList
    |> Seq.map fetchAsync
    |> Async.Parallel 
    |> Async.RunSynchronously
    |> ignore

runAll()

您可以使用Futures將代碼更多或更少直接轉換為Scala(但丟失了一些重要功能):

import scala.actors.Futures
import Futures._

val urlList = Map("Microsoft.com" -> "http://www.microsoft.com/",
                "MSDN" -> "http://msdn.microsoft.com/",
                "Bing" -> "http://www.bing.com")


def fetchAsync(name: String, url: String) = future {
    // lengthy operation simulation
    Thread.sleep(1000)
    println("Fetching from %s: %s" format(name, url))
}

def runAll = 
    //Futures.awaitAll(  <- if you want to synchronously wait for the futures to complete 
    urlList.map{case (name, url) => fetchAsync(name, url)}
    //)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM