为了学习,我写了一个Scala代码
package pk
abstract class tree {
def contains(x: Int): Boolean
def incl(x: Int): tree
def union(other: tree): tree
}
class empty extends tree {
def contains(x: Int): Boolean = false
def incl(x: Int): tree = new nonEmpty(x, new empty, new empty)
override def toString = "."
def union(other: tree): tree = {
other
}
}
class nonEmpty(elem: Int, left: tree, right: tree) extends tree {
def contains(x: Int): Boolean = {
if (x < elem) left contains x
else if (x > elem) right contains x
else true
}
def incl(x: Int): tree = {
if (x < elem) new nonEmpty(elem, left incl x, right)
else if (x > elem) new nonEmpty(elem, left, right incl x)
else
this
}
def union(other: tree): tree = {
((left union right) union other) incl elem
}
if (true) 1 else false
override def toString = "{" + left + elem + right + "}"
}
并制作相同包装的一部分
package pk
object genric {
val h10 = new nonEmpty(90, new empty, new empty)
val h9 = new empty()
var h11 = new cons(h10, nil)
list.f(h11, h9)
// val h9=new nonEmpty(5,new empty,new empty)
}
trait List[+T] {
def head: T
def tail: List[T]
def isEmpty: Boolean
def prepend[u >: T](elem: u): List[u] = new cons(elem, this)
}
class cons[T](var head: T, val tail: List[T]) extends List[T] {
def isEmpty = false
}
object nil extends List[Nothing] {
def isEmpty = true
def tail = throw new NoSuchElementException
def head = throw new NoSuchElementException
}
object list {
def apply[T](a: T, b: T) = new cons(a, new cons(b, nil))
def apply = nil
def f(xs: List[nonEmpty], x: empty) = xs prepend x
}
当我使用scala解释器运行它时,它说我的方法中找不到nonEmpty F() 我无法理解为什么它给我错误,虽然我有相同包中的文件
答案 0 :(得分:0)
因为Scala解释器从上到下读取文件,所以在使用之前需要确保声明了一个类。因此,在第一个文件中,您需要移动nonEmpty声明并首先读取该文件。
第一档:
abstract class tree {
def contains(x: Int): Boolean
def incl(x: Int): tree
def union(other: tree): tree
}
class nonEmpty(elem: Int, left: tree, right: tree) extends tree {
def contains(x: Int): Boolean = {
if (x < elem) left contains x
else if (x > elem) right contains x
else true
}
def incl(x: Int): tree = {
if (x < elem) new nonEmpty(elem, left incl x, right)
else if (x > elem) new nonEmpty(elem, left, right incl x)
else
this
}
def union(other: tree): tree = {
((left union right) union other) incl elem
}
if (true) 1 else false
override def toString = "{" + left + elem + right + "}"
}
class empty extends tree {
def contains(x: Int): Boolean = false
def incl(x: Int): tree = new nonEmpty(x, new empty, new empty)
override def toString = "."
def union(other: tree): tree = {
other
}
}