加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 如何使用Kleisli组合与返回验证的功能?

发布时间:2020-12-16 09:19:34 所属栏目:安全 来源:网络整理
导读:如何撰写返回验证的两个函数?以下是我未尝试的尝试: scala def f: Int = Validation[String,Int] = i = if(i % 2 == 0) Success(i * 2) else Failure("Odd!")f: Int = scalaz.Validation[String,Int]scala def g: Int = Validation[String,Int] = i = if(i
如何撰写返回验证的两个函数?以下是我未尝试的尝试:

scala> def f: Int => Validation[String,Int] = i => if(i % 2 == 0) Success(i * 2) else Failure("Odd!")
f: Int => scalaz.Validation[String,Int]

scala> def g: Int => Validation[String,Int] = i => if(i > 0) Success(i + 1) else Failure("Not positive!")
g: Int => scalaz.Validation[String,Int]

scala> kleisli(f) >=> kleisli(g)
<console>:16: error: no type parameters for method kleisli: (f: A => M[B])scalaz.Kleisli[M,A,B] exist so that it can be applied to arguments (Int => scalaz.Validation[String,Int])
 --- because ---
argument expression's type is not compatible with formal parameter type;
 found   : Int => scalaz.Validation[String,Int]
 required: ?A => ?M[?B]

              kleisli(f) >=> kleisli(g)
              ^

scala> type Va[+A] = Validation[String,A]
defined type alias Va

scala> kleisli[Va,Int,Int](f) >=> kleisli[Va,Int](g)
<console>:17: error: could not find implicit value for parameter b: scalaz.Bind[Va]
              kleisli[Va,Int](g)
                                       ^

这在Haskell工作,所以我期待着应该有一种这样做与Scalaz的方式.

λ> let f i = if i `mod` 2 == 0 then Right $i * 2 else Left "Odd!"
λ> let g i = if i > 0 then Right $i + 1 else Left "Not positive!"
λ> let h = f >=> g
λ> h 11
Left "Odd!"
λ> h (-4)
Left "Not positive!"
λ> h 4
Right 9

解决方法

您需要导入Validation.Monad._,因为> =>需要绑定[M]

scala> import scalaz._,Scalaz._
import scalaz._
import Scalaz._

scala> def f: Int => Validation[String,Int] = i => if(i % 2 == 0) Success(i * 2) else    Failure("Odd!")
f: Int => scalaz.Validation[String,Int]

scala> type Va[+A] = Validation[String,A]
defined type alias Va

scala> import Validation.Monad._
import Validation.Monad._

scala> kleisli[Va,Int](g)
res0: scalaz.Kleisli[Va,Int] = scalaz.Kleislis$$anon$1@4fae3fa6

scala> res0(11)
res1: Va[Int] = Failure(Odd!)

scala> res0(-4)
res2: Va[Int] = Failure(Not positive!)

scala> res0(4)
res3: Va[Int] = Success(9)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读