Martin Thompson
Martin Thompson

Reputation: 3745

How to get the String Value of a Json element on the Same line in F#

I have some code that I would like to put on the same line instead of having separate variable ( maybe pipe? )

    let! creditText = row.EvalOnSelectorAsync("div.moneyout","node => node.innerText") |> Async.AwaitTask
    let JSonElementString = creditText.Value.GetString()

I would like to have something like:

let! creditText = row.EvalOnSelectorAsync("div.moneyout","node => node.innerText") |> Async.AwaitTask |> (fun js -> js.Value.GetString)

I can see what is happening - at the point of the function the variable is still async. How can I make it pipe the result through to a function on the same line?

Upvotes: 1

Views: 83

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243041

I do not understand why you want to do this. The code is perfectly readable and succinct when it is written as two lines. Condensing it into a single line only makes it harder to understand.

That said, if you wanted to do this, the best option would be to have a map operation for either Async<T> or Task<T>. This exists in various libraries, but you can also easily define it yourself:

module Async = 
  let map f a = async { 
    let! r = a
    return f a }

Using this, you can now write:

let! creditText = 
  row.EvalOnSelectorAsync("div.moneyout","node => node.innerText") 
  |> Async.AwaitTask 
  |> Async.map (fun creditText -> creditText.Value.GetString())

But as I said above, I think this is a bad idea and your two-line version is nicer.

Upvotes: 3

Related Questions