Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 268
pharoah 121 Avatar asked Apr 07 '11 10:04

pharoah 121


People also ask

What is F type Scala?

The F[_] simply means that F is a type parameter , which is itself a type constructor or a type with a type parameter . As we stated earlier, such a type can be a List , Option , or even a Scala Future .

What is F interpolation in Scala?

The f Interpolator Prepending f to any string literal allows the creation of simple formatted strings, similar to printf in other languages. When using the f interpolator, all variable references should be followed by a printf -style format string, like %d . Let's look at an example: Scala 2 and 3.

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

What is string * in Scala?

Scala string is an immutable object that means the object cannot be modified. Each element of a string is associated with an index number. The first character is associated with the number 0, the second with the number 1, etc. Class java. lang.


1 Answers

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)}
    //)
like image 176
Vasil Remeniuk Avatar answered Nov 05 '22 14:11

Vasil Remeniuk