【问题标题】:symbolic differentiation in ScalaScala中的符号微分
【发布时间】:2012-03-02 19:43:33
【问题描述】:

我想在 Scala 中使用它的模式匹配来创建一个符号微分函数,就像在 SICP 中所做的那样。我希望能够写出这样的东西:

differentiate(exp) = exp match
{
  case + => 
  case * =>
}

这在 Scala 中的“本机”表达式上是否可行?

【问题讨论】:

  • 你的意思是def differentiate (exp: T) = ...? exp是什么类型的?一个字符串?一个函数?两者都不适合仅使用“+”或“*”。
  • 也许这是您提出问题的灵感来源,但如果您还没有看到,请参阅 Scala 编程 (artima.com/pins1ed/case-classes-and-pattern-matching.html) 的模式匹配章节中的扩展示例
  • @LuigiPlinge 确实有人建议我,但我想看看我是否需要自己制作这棵树。

标签: scala math sicp symbolic-math


【解决方案1】:

你试过了吗? :)

sealed trait Exp
case object + extends Exp
case object * extends Exp

def differentiate(exp: Exp) = exp match {
  case + => println("plus")
  case * => println("times")
}

scala> differentiate(*)
times

但是

scala> differentiate(+)
<console>:1: error: illegal start of simple expression
       differentiate(+)
                  ^

嗯,我猜它不适用于所有符号。

【讨论】:

  • 虽然你可以用differentiate($plus)来调用它。
  • '+' 的问题是错误吗?
  • @soc 我不特别了解+,但您当然希望某些符号(保留字符,如{; 等)不起作用。跨度>
【解决方案2】:

我之前见过的每个例子都涉及到一个表达式树。您可以使用案例类在 Scala 中轻松构建它。例如,涉及模式匹配和面向对象风格的粗略草图:

trait Exp {
  def differentiate: Exp
}
case class Const( value: Double ) extends Exp {
  def differentiate = Const(0)
}
case class Var( label: String, power: Double ) extends Exp {
  def differentiate = this match {
    case Var(l,0.0) => Const(0)
    case Var(l,p) => Mul( Const(p), Var(l,p-1) )
  }
}
case class Add( left: Exp, right: Exp ) extends Exp {
  def differentiate = Add( left.differentiate, right.differentiate )
}
case class Mult( left: Exp, right: Exp ) extends Exp {
  def differentiate = ( left, right ) match {
    case ( Const(c), exp ) => Mul( Const(c), exp.differentiate )
    case ( exp, Const(c) ) => Mul( Const(c), exp.differentiate )
    case (e1, e2) => Add( Mul( e1.differentiate, e2), Mul( e1, e2.differentiate ) )
  }
}

【讨论】:

    【解决方案3】:

    关于“本地”表达,没有。并不真地。你可以使用符号:

    def foo(x: Symbol) = x match {
      case '+ => "Plus"
      case '* => "Times"
    }
    

    如果您注意到,符号也是 SICP 解析事物的方式。见SICP 2.3.1

    (deriv '(* x y) 'x)
    y
    

    它可能有更漂亮的符号匹配语法,但最终,这就是它所做的一切。

    【讨论】:

      猜你喜欢
      • 2017-09-13
      • 2014-08-10
      • 2015-02-13
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多