Order of arguments and pipe-right operator

2019-09-02 17:19发布

问题:

Is there a way to simplify the following, so I won't need a runWithTimeout function?

let runWithTimeout timeout computation =
   Async.RunSynchronously(computation, timeout)

let processOneItem item =  fetchAction item
                           |> runWithTimeout 2000

Edit: Here's why i needed the extra method:

let processOneItem item =  fetchAction item
                           |> Async.Catch
                           |> runWithTimeout 2000
                           |> handleExceptions

回答1:

Perhaps you mean something like this:

let processOneItem item =
  fetchAction item
  |> fun x -> Async.RunSynchronously(x, 2000)


回答2:

I'm not very keen on using fun x -> ... as part of a pipeline.

I think that the pipelining style of writing code is nice when it is supported by the API (e.g. lists), but when the API doesn't fit the style, it is just better to follow the usual "C#-like" style. Of coures, this is just a personal preference, but I'd just write:

let processOneItem item =  
  let work = Async.Catch(fetchAction item)
  let result = Async.RunSynchronously(work, 30000)
  handleExceptions result


回答3:

Here's a more complete sample, for future reference:

let processOneItem item =  fetchAction item
                           |> Async.Catch
                           |> fun x -> Async.RunSynchronously(x,30000)
                           |> handleExceptions