繁体   English   中英

使用优化重试?

[英]Using Refined for Retry?

使用精致,我尝试定义f

import eu.timepit.refined._
import eu.timepit.refined.api.Refined
import eu.timepit.refined.auto._
import eu.timepit.refined.numeric._

// if action 'succeeds', return 'good'; otherwise re-try, subtracting count by 1
scala> def f[A](action: => A, success: A => Boolean, count: Int Refined Positive): String = 
     |   if( success(action) ) "good" else f(action, success, count - 1)
<console>:32: error: compile-time refinement only works with literals
         if( success(action) ) "good" else f(action, success, count - 1)
                                                                    ^

既然那行不通,我求助于:

def fEither[A](action: => A, success: A => Boolean, count: Either[String, Int Refined Positive]): String = { 
  println(count)

  if( success(action) ) "good" 
  else {
    count match {
      case Right(c) => fEither(action, success, refineV[Positive](c - 1))
      case Left(_)  => "bad"
    }
  }
}

scala> fEither[Int](42, _ => false, Right( refineMV[Positive]( 2 ) ) )
Right(2)
Right(1)
Left(Predicate failed: (0 > 0).)
res2: String = bad

理想情况下,我想将此Idris程序转换为Scala:

f : (action : a) -> (success: a -> Bool) -> (n : Nat) -> String
f action success (S n) = if (success action) then "good" else f action success n
f _       _      Z     = "bad"

*scratch> f 42 (const False) 2
"bad" : String
*scratch> f 42 (const False) 0
"bad" : String

但我不确定Nat功能是否与任何模式匹配。

  • 您要使用的优化是NonNegative ,因此0是有效值。
  • Idris代码本质上区分n - 1是否仍然是自然数,因此您可以使用运行时版本refineV直接进行refineV

def f[A](action: => A, success: A => Boolean, count: Int Refined NonNegative): String =
  refineV[NonNegative](count - 1) match {
    case Right(n) => if (success(action)) "good" else f(action, success, n)
    case Left(_)  => "bad"
  }

PS您可能希望多个参数列表b / c Scala可能无法在呼叫站点正确推断A的类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM