Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining F# async functions

I'm a bit frustrated here. I know I've got all the bits, but I can't work out how to combine them...

let saveImageToDisk path content =
    async {
        use s = new FileStream(path, FileMode.OpenOrCreate)
        do! s.AsyncWrite(content)
        printfn "Done writing %A" path
        } // returns Async<unit>

let getImages imageUrls =
    imageUrls
        |> Seq.map (fun url -> topath url, getImage url)
        //Next line not happy because content is Async<byte[]> instead of byte[]
        |> Seq.map (fun (path, content) -> saveImageToDisk path content)
        |> Async.Parallel
        |> Async.RunSynchronously
like image 415
Benjol Avatar asked Apr 17 '11 11:04

Benjol


People also ask

Can you combine 2 functions?

Become familiar with the idea that we can add, subtract, multiply, or divide two functions together to make a new function. Just like we can add, subtract, multiply, and divide numbers, we can also add, subtract, multiply, and divide functions.

How do you plug functions into each other?

The process of plugging one function into another is called the composition of functions. When one function is composed with another, it is usually written explicitly: f( g( x)), which is read “ f of g of x.” In other words, x is plugged into g, and that result is in turn plugged into f.


1 Answers

You can combine the two using the async expression:

let getImages imageUrls =
    imageUrls
        |> Seq.map (fun url -> async {
              let! content = getImage url
              return! saveImageToDisk (topath url) content })
        |> Async.Parallel
        |> Async.RunSynchronously
like image 53
Talljoe Avatar answered Sep 30 '22 09:09

Talljoe