0

I'm using StackExchange.Redis inside a small F# project and I need to cast the db.StringGetAsync() return value to an int. I've found a way to do it like this:

let! intFromRedis= async {
    let! value = db.StringGetAsync(key) |> Async.AwaitTask 
    return int value
}

But it would be prettier to be able to do something like this instead:

// Better syntax but it does not compile
let! intFromRedis : int = db.StringGetAsync(key) |> Async.AwaitTask

Is there a better syntax for this?

8
  • I can't try this where I am, but can't you just add |> int at the end? Commented Feb 18, 2015 at 10:15
  • @MarkPattison: The type 'Async<RedisValue>' does not support a conversion to the type 'int' Commented Feb 18, 2015 at 10:41
  • Perhaps you could use the Async.map Tomas Petricek describes here: stackoverflow.com/a/6793961/126014 Commented Feb 18, 2015 at 11:32
  • The Async.map example worked. Please answer the question so that I can approve it. Commented Feb 18, 2015 at 11:50
  • Why not just cast to int on a second line, or right where you use the value? It sounds like overkill to define and use Async.map just to maybe save one line of code. Commented Feb 18, 2015 at 12:47

1 Answer 1

2

As has been pointed out in the comments, technically, the question asks for Async.map, which could be defined similar to the code in the question.

But I'd rather recommend to keep it simple. Casting on a second line would look like this:

let! redisValue = db.StringGetAsync(key) |> Async.AwaitTask
let intFromRedis = int redisValue

And I'm not even sure intFromRedis is more readable than int redisValue. It's barely shorter, and the latter expression is self-explanatory. Thus, there's no real problem in keeping just the first line and using int redisValue.

Using rare or custom functions reduces readability. A cast – and maybe a value binding – are simple, short enough, and any programmer reading the code should understand what is happening.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree that Async.map is overkill.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.