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

心不动则不痛 提交于 2019-11-30 14:42:02

问题


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

For example, how would following F# snippet translate to idiomatic 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()

回答1:


You code more or less directly can be translated to Scala using Futures (with some important features lost, though):

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)}
    //)


来源:https://stackoverflow.com/questions/5579602/what-is-the-scala-equivalent-of-fs-async-workflows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!