什么是Scala等同于F#的异步工作流?
发布时间:2020-12-16 09:19:55 所属栏目:安全 来源:网络整理
导读:什么是Scala等同于F#的异步工作流? 例如,F#代码段如何转换成惯用的Scala? open System.Netopen Microsoft.FSharp.Control.WebExtensionslet urlList = [ "Microsoft.com","http://www.microsoft.com/" "MSDN","http://msdn.microsoft.com/" "Bing","http:/
什么是Scala等同于F#的异步工作流?
例如,F#代码段如何转换成惯用的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() 解决方法
您的代码或多或少直接可以翻译成Scala使用Futures(有一些重要功能丢失,虽然):
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)} //) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |