小编roe*_*lio的帖子

创建二叉树scala的和树

对于家庭作业,我写了一些scala代码,其中我有以下类和对象(用于建模二叉树):

object Tree {
  def fold[B](t: Tree, e: B, n: (Int, B, B) => B): B = t match {
    case Node(value, l, r) => n(value,fold(l,e,n),fold(r,e,n))
    case _ => e
  }
  def sumTree(t: Tree): Tree = 
    fold(t, Nil(), (a, b: Tree, c: Tree) => {
      val left = b match {
        case Node(value, _, _) => value
        case _ => 0
      }
      val right = c match {
        case Node(value, _, _) => value
        case _ => 0
      }
      Node(a+left+right,b,c) …
Run Code Online (Sandbox Code Playgroud)

binary-tree functional-programming scala

12
推荐指数
1
解决办法
4471
查看次数

无法在scala中捕获ClassCastException

我在捕获ClassCastException时遇到了一些问题.它发生在检索函数的模式匹配的最后一种情况下,例外是不正确的.

我怎样才能解决这个问题?

  abstract class Property

  object EmptyProperty extends Property

  class PropertyCompanion[T]

  object Type extends PropertyCompanion[Type]
  case class Type extends Property

  object Name extends PropertyCompanion[Name]
  case class Name extends Property

  abstract class Entity {
    protected val properties: Map[PropertyCompanion[_], Property]
    def retrieve[T](key: PropertyCompanion[T]) =
      properties.get(key) match {
        case Some(x) => x match {
          case EmptyProperty => throw new Exception("empty property")
          case _ => {
            try {
              x.asInstanceOf[T]
            } catch {
              case e => throw new Exception("fubar")
            }
          }
        }
        case None => …
Run Code Online (Sandbox Code Playgroud)

scala exception-handling pattern-matching

4
推荐指数
1
解决办法
956
查看次数

使用大量自我类型的mixins

我想构建一些scala类来模拟RDF.我有课程和财产.属性被混合到类中,并且properties由于它们的自身类型可以使用hashmap.

随着类获得更多属性,我必须使用大量mixins(50+),我想知道这是否仍然是一个明智的解决方案?

trait Property

trait Properties {
  val properties = 
    new scala.collection.mutable.HashMap[String, Property]
}

abstract class AbstractClass extends Properties

trait Property1 {
  this: AbstractClass =>
    def getProperty1 = properties.get("property1")
}

trait Property100 {
  this: AbstractClass =>
    def getProperty100 = properties.get("property100")
}

class Class1 extends AbstractClass
    with Property1 with Property100
Run Code Online (Sandbox Code Playgroud)

rdf scala mixins

3
推荐指数
1
解决办法
195
查看次数