11

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

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

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

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]                                    ^
4

2 回答 2

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所需的类型。

于 2012-02-23T18:37:02.560 回答
2

请注意,因为ReaderValidation(带有半群 E)都是 Applicative,所以它们的组合也是 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"))
于 2012-08-11T07:56:46.213 回答