abstract class MyList[ A] {
def head: A
def next: MyList[A]
def isEmpty: Boolean
def add[B >: A](element: B): MyList[B]
def printElements: String
override def toString: String = s"[$printElements]"
def [B >: A](list: MyList[B]): MyList[B]
def ::[B >: A](list: MyList[B]): MyList[B]
}
case object Empty extends MyList[Nothing] {
def head: Nothing = throw new NoSuchElementException
def next: MyList[Nothing] = throw new NoSuchElementException
def isEmpty: Boolean = true
def add[B >: Nothing](element: B): MyList[B] = Cons(element, Empty)
def printElements: String = ""
def [B >: Nothing](list: MyList[B]): MyList[B] = list
def ::[B >: Nothing](list: MyList[B]): MyList[B] = list
}
case class Cons[ A](h: A, t: MyList[A]) extends MyList[A] {
def this(h: A) = this(h, Empty)
def head: A = h
def next: MyList[A] = t
def isEmpty: Boolean = false
def add[B >: A](element: B): MyList[B] = Cons(element, this)
def printElements: String =
if (t.isEmpty) s"$h"
else s"$h ${t.printElements}"
def [B >: A](list: MyList[B]): MyList[B] = Cons(h, next list)
def ::[B >: A](list: MyList[B]): MyList[B] = Cons(h, next :: list)
}
object runTest extends App {
val a = Empty.add(1).add(2).add(3)
val b = Empty.add(4).add(5).add(6)
println(a)
println(b)
println(a b) //[3 2 1 6 5 4] good
println(a :: b) //[6 3 5 2 4 1] why???
}
我試圖連接兩個 MyList,但問題是,“ ”和“::”具有相同的邏輯,但“ ”將列印 [3 2 1 6 5 4],這是有道理的,而“::”將列印 [6 3 5 2 4 1]
uj5u.com熱心網友回復:
從2.13 語言規范(我似乎找不到 scala3 版本,但這部分沒有改變):
以冒號 ':' 結尾的運算子是右結合的。所有其他運算子都是左結合的。
[...]
如果
op是右關聯且其引數按名稱傳遞,則相同的操作被解釋為e2.op(e1)
所以你a :: b的和b.::(a), 和
def ::[B >: A](list: MyList[B]): MyList[B] = Cons(h, next :: list)
是
def ::[B >: A](list: MyList[B]): MyList[B] = Cons(h, list.::(next))
這解釋了[6 3 5 2 4 1]你得到的。
你可以通過使用得到你想要的結果
def ::[B >: A](list: MyList[B]): MyList[B] = Cons(h, next.::(list))
...
println(a.::(b))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/412123.html
標籤:
上一篇:列舉的Python比較?
