F#异步工作流的Scala等效项是什么? [英] What is the Scala equivalent of F#'s async workflows?

查看:68
本文介绍了F#异步工作流的Scala等效项是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala等价于F#的异步工作流程?

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

例如,以下F#代码段将如何转换为惯用的Scala?

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()

推荐答案

您可以使用Futures直接将您的代码或多或少直接翻译为Scala(尽管有些重要功能丢失了):

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

这篇关于F#异步工作流的Scala等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆