Repeat expression or other construct in F #

I want to write a calculation expression in F # that can repeat the operation if it throws an exception. My code now looks like this:

let x = retry (fun() -> GetResourceX())
let y = retry (fun() -> GetResourceY())
let z = retry (fun() -> DoThis(x, y))
etc. (this is obviously an astract representation of the actual code)

I need to be able to repeat each function a certain number of times, which I defined in elswhere.

I thought a calculation expression could help me here, but I don't see how this could help me explicitly remove each right side in Retryable <'T>

I could see a calculation expression that looked something like this:

let! x = Retryable( fun() -> GetResourceX())
etc.

I understand that Monads, in a crude way, are types of wrappers, but I was hoping for that. I know that I can overload the operator and have very concise syntax for converting the operation to Retryable <'T>, but for me it just makes the repeat / wrap more compressed; he is still there. I could wrap each function as Retryable <'T>, but once again, I don’t see a value over what was being done at the top of the message (the retry call on each operation is at least very explicit).

Maybe the computation expressions are a wrong abstraction here, I'm not sure. Any ideas on what you can do here?

+3
source share
3 answers

( ), .

, (, , Retryable<'T>), . F # Run, , retry { return 1 } int.

( ):

let rnd = new System.Random()
// The right-hand side evaluates to 'int' and automatically
// retries the specified number of times
let n = retry { 
  let n = rnd.Next(10)
  printfn "got %d" n
  if n < 5 then failwith "!"  // Throw exception in some cases
  else return n }

// Your original examples would look like this:
let x = retry { return GetResourceX() }
let y = retry { return GetResourceY() }
let z = retry { return DoThis(x, y) }

retry. , let! ( , retry retry, X-, Y- ).

type RetryBuilder(max) = 
  member x.Return(a) = a               // Enable 'return'
  member x.Delay(f) = f                // Gets wrapped body and returns it (as it is)
                                       // so that the body is passed to 'Run'
  member x.Zero() = failwith "Zero"    // Support if .. then 
  member x.Run(f) =                    // Gets function created by 'Delay'
    let rec loop(n) = 
      if n = 0 then failwith "Failed"  // Number of retries exceeded
      else try f() with _ -> loop(n-1)
    loop max

let retry = RetryBuilder(4)
+6

.

let rec retry times fn = 
    if times > 1 then
        try
            fn()
        with 
        | _ -> retry (times - 1) fn
    else
        fn()

.

let rnd = System.Random()

let GetResourceX() =
    if rnd.Next 40 > 1 then
        "x greater than 1"
    else
        failwith "x never greater than 1" 

let GetResourceY() =
    if rnd.Next 40 > 1 then
        "y greater than 1"
    else
        failwith "y never greater than 1" 

let DoThis(x, y) =
    if rnd.Next 40 > 1 then
        x + y
    else
        failwith "DoThis fails" 


let x = retry 3 (fun() -> GetResourceX())
let y = retry 4 (fun() -> GetResourceY())
let z = retry 1 (fun() -> DoThis(x, y))
+2

Here is the first attempt to do this in one calculation expression. But be careful that this is only a first attempt; I did not check it . Also, it is a little ugly when re-setting the number of attempts in a calculation expression. I think the syntax could be cleaned up in this basic structure.

let rand = System.Random()

let tryIt tag =
  printfn "Trying: %s" tag
  match rand.Next(2)>rand.Next(2) with
  | true -> failwith tag
  | _ -> printfn "Success: %s" tag

type Tries = Tries of int

type Retry (tries) =

  let rec tryLoop n f =
    match n<=0 with
    | true -> 
      printfn "Epic fail."
      false
    | _ -> 
      try f()
      with | _ -> tryLoop (n-1) f 

  member this.Bind (_:unit,f) = tryLoop tries f 
  member this.Bind (Tries(t):Tries,f) = tryLoop t f
  member this.Return (_) = true

let result = Retry(1) {
  do! Tries 8
  do! tryIt "A"
  do! Tries 5
  do! tryIt "B"
  do! tryIt "C" // Implied: do! Tries 1
  do! Tries 2
  do! tryIt "D" 
  do! Tries 2
  do! tryIt "E"
}


printfn "Your breakpoint here."

ps But I like the versions of Tomas and gradbot. I just wanted to see what this type of solution looks like.

0
source

All Articles