2016-05-28 8 views
0

私はラムダ微積分クラスのために怠惰な無限リストの機能をプロトタイプ化するためにScalaを使用しようとしています。 publicコンストラクタは2つの引数をとり、LazyList [A、A]を作成する必要があります。スカラ型の不一致が複数の汎用を使用して

class LazyList[A,B] private (private val first: A, private val mapper: A => B, private val successor: A => A) { 
    def this(first: A, successor: A => A) = this(first, (e: A) => e, successor) 

    def head: B = mapper(first) 

    def tail(): LazyList[A,B] = new LazyList(successor(first), mapper, successor) 
    def map[R](func: B => R) = new LazyList[A, R](first, func.compose(mapper), successor) 
    def at(index: Long): B = if (index == 0L) head else tail().at(index - 1) 
    def sublist(end: Long): List[B] = if (end == 0L) List(head) else head :: tail().sublist(end - 1) 

    override def toString = s"LazyList($first, $mapper, $successor)" 
} 

しかし、コードのコンパイルはエラーで失敗します。

Error:(20, 65) type mismatch; 
found : e.type (with underlying type A) 
required: B 
    def this(first: A, successor: A => A) = this(first, (e: A) => e, successor) 
                  ^

実際には間違っていますか?それはコンパイラが時に文句理由です、クラス内の

答えて

2

パラメータ化された署名はAを入力するタイプBの関係についての情報を持っていないため、コンパイラは、一般的にどこにでもLazyListの体内BAではないと考えていますA => AA => Bを割り当てようとしています。

this()ではなく、コンパニオンオブジェクトのファクトリメソッドとして代替コンストラクタを作成する必要があります。この使用法のAは、LazyListの本体内にあるAにはまったく関係のないパラメータです。

object LazyList { 
    def apply[A](first: A, successor: A => A): LazyList[A, A] = new LazyList(first, identity, successor) 
} 
関連する問題