如何用scalaz组成应用程序的功能

时间:2012-02-23 07:00:32

标签: validation scala scalaz applicative

在学习 Scalaz 6 时,我正在尝试编写类型安全的读者返回验证。以下是我的新类型:

type ValidReader[S,X] = (S) => Validation[NonEmptyList[String],X]
type MapReader[X] = ValidReader[Map[String,String],X]

我有两个函数为int和字符串创建地图阅读器(*):

def readInt( k: String ): MapReader[Int] = ...
def readString( k: String ): MapReader[String] = ...

给出以下地图:

val data = Map( "name" -> "Paul", "age" -> "8" )

我可以写两个读者来检索姓名和年龄:

val name = readString( "name" )
val age = readInt( "age" )

println( name(data) ) //=> Success("Paul")
println( age(data) )  //=> Success(8)

一切正常,但现在我想组建两个读者来构建一个Boy实例:

case class Boy( name: String, age: Int )

我最好的选择是:

  val boy = ( name |@| age ) {
    (n,a) => ( n |@| a ) { Boy(_,_) }
  }
  println( boy(data) ) //=> Success(Boy(Paul,8))

它按预期工作,但表达式很尴尬,有两个级别的应用程序构建器。有没有办法让下面的语法起作用?

  val boy = ( name |@| age ) { Boy(_,_) }

(*)完整且可运行的实现:https://gist.github.com/1891147


更新:以下是我在尝试上述行或Daniel建议时收到的编译器错误消息:

[error] ***/MapReader.scala:114: type mismatch;
[error]  found   : scalaz.Validation[scalaz.NonEmptyList[String],String]
[error]  required: String
[error]   val boy = ( name |@| age ) { Boy(_,_) }
[error]                                    ^

2 个答案:

答案 0 :(得分:5)

这个怎么样?

val boy = (name |@| age) {
  (Boy.apply _).lift[({type V[X]=ValidationNEL[String,X]})#V]
}

或使用类型别名:

type VNELStr[X] = ValidationNEL[String,X]

val boy = (name |@| age) apply (Boy(_, _)).lift[VNELStr]

这是基于控制台上的以下错误消息:

scala> name |@| age apply Boy.apply
<console>:22: error: type mismatch;
 found   : (String, Int) => MapReader.Boy
 required: (scalaz.Validation[scalaz.NonEmptyList[String],String], 
            scalaz.Validation[scalaz.NonEmptyList[String],Int]) => ?

所以我刚刚举起Boy.apply来取得所需的类型。

答案 1 :(得分:2)

请注意,由于ReaderValidation(带有半群E)都是Applicative,因此它们的组成也是适用的。使用scalaz 7可以表示为:

import scalaz.Reader
import scalaz.Reader.{apply => toReader}
import scalaz.{Validation, ValidationNEL, Applicative, Kleisli, NonEmptyList}

//type IntReader[A] = Reader[Int, A] // has some ambigous implicit resolution problem
type IntReader[A] = Kleisli[scalaz.IdInstances#Id, Int, A]
type ValNEL[A] = ValidationNEL[Throwable, A]

val app = Applicative[IntReader].compose[ValNEL]

现在我们可以在撰写的Applicative:

上使用单个|@|操作
val f1 = toReader((x: Int) => Validation.success[NonEmptyList[Throwable], String](x.toString))
val f2 = toReader((x: Int) => Validation.success[NonEmptyList[Throwable], String]((x+1).toString))

val f3 = app.map2(f1, f2)(_ + ":" + _)

f3.run(5) should be_==(Validation.success("5:6"))