2015-10-06 44 views
2

我正在寻找一种方法来捕获在理解本身的类型中用于理解的类型。为此,我所指定的粗糙界面:用于理解的捕获和链接类型

trait Chain[A]{ 
    type ChainMethod = A => A //type of the method chained so far 

    def flatMap[B](f: A => Chain[B]): Chain[B] //the ChainMethod needs to be included in the return type somehow 
    def map[B](f: A => B): Chain[B]: Chain[B] 

    def fill: ChainMethod //Function has to be uncurried here 
} 

作为例子的几个具体类型的Chain

object StringChain extends Chain[String] 
object IntChain extends Chain[Int] 

和壳体类,将被使用:

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

A链可以创建一个for理解:

val form = for{ 
    name <- StringChain 
    age <- IntChain 
} yield User(name, age) 

form类型应该是

Chain[User]{type ChainMethod = String => Int => User} 

,使我们可以做到以下几点:

form.fill("John", 25) //should return User("John", 25) 

我尝试了一些方法,以结构类型和专业FlatMappedChain特质,但我不能让类型系统按照我希望的方式行事。我会喜欢关于如何指定接口的一些想法或建议,以便编译器可以认识到这一点,如果这是可能的话。

回答

1

我认为在Scala中从零开始很难做到这一点。您可能必须为不同元素的函数定义大量隐式类。

如果使用专门用于类型级计算的shapeless库,它将变得更加容易。以下代码使用稍微不同的方法,其中Chain.fill是从参数元组到结果的函数。的flatMap此实现还允许几种形式组合成一个:

import shapeless._ 
import shapeless.ops.{tuple => tp} 

object Chain { 
    def of[T]: Chain[Tuple1[T], T] = new Chain[Tuple1[T], T] { 
    def fill(a: Tuple1[T]) = a._1 
    } 
} 

/** @tparam A Tuple of arguments for `fill` 
    * @tparam O Result of `fill` 
    */ 
abstract class Chain[A, O] { self => 
    def fill(a: A): O 

    def flatMap[A2, O2, Len <: Nat, R](next: O => Chain[A2, O2])(
    implicit 
     // Append tuple A2 to tuple A to get a single tuple R 
     prepend: tp.Prepend.Aux[A, A2, R], 
     // Compute length Len of tuple A 
     length: tp.Length.Aux[A, Len], 
     // Take the first Len elements of tuple R, 
     // and assert that they are equivalent to A 
     take: tp.Take.Aux[R, Len, A], 
     // Drop the first Len elements of tuple R, 
     // and assert that the rest are equivalent to A2 
     drop: tp.Drop.Aux[R, Len, A2] 
): Chain[R, O2] = new Chain[R, O2] { 
    def fill(r: R): O2 = next(self.fill(take(r))).fill(drop(r)) 
    } 

    def map[O2](f: O => O2): Chain[A, O2] = new Chain[A, O2] { 
    def fill(a: A): O2 = f(self.fill(a)) 
    } 
} 

这里是你如何使用它:

scala> case class Address(country: String, city: String) 
defined class Address 

scala> case class User(id: Int, name: String, address: Address) 
defined class User 

scala> val addressForm = for { 
    country <- Chain.of[String] 
    city <- Chain.of[String] 
} yield Address(country, city) 
addressForm: com.Main.Chain[this.Out,Address] = [email protected] 

scala> val userForm = for { 
    id <- Chain.of[Int] 
    name <- Chain.of[String] 
    address <- addressForm 
} yield User(id, name, address) 
userForm: com.Main.Chain[this.Out,User] = [email protected] 

scala> userForm.fill(1, "John", "USA", "New York") 
res0: User = User(1,John,Address(USA,New York))