fork download
  1. object SymbolicExpressions {
  2. type Variable = () => Unit
  3. type Context = Variable => Float
  4. type Expression = Context => Float
  5. type Operator = (Expression, Expression) => Expression
  6.  
  7. def variable = () => ()
  8.  
  9. def value(variable: Variable)(context: Context) = context(variable)
  10.  
  11. def constant(value: Float)(context: Context) = value
  12.  
  13. def operator(floatOperator: (Float, Float) => Float)(a: Expression, b: Expression)(context: Context) = {
  14. floatOperator(a(context), b(context))
  15. }
  16.  
  17. val plus: Operator = operator(_ + _)
  18. val minus: Operator = operator(_ - _)
  19. val multiply: Operator = operator(_ * _)
  20. val divide: Operator = operator(_ / _)
  21. }
  22.  
  23. object Main extends App {
  24. import SymbolicExpressions._
  25.  
  26. def sqrt(x: Expression)(context: Context) = math.sqrt(x(context)).toFloat
  27.  
  28. val a = variable
  29. val b = variable
  30. val c = variable
  31. val d = variable
  32.  
  33. val expression = plus(minus(multiply(divide(value(a), value(b)), value(c)), value(d)), sqrt(constant(25f)))
  34.  
  35. val context = Map(a -> 1f, b -> 2f, c -> 3f, d -> 4f)
  36. println(expression(context))
  37. }
Success #stdin #stdout 0.43s 322432KB
stdin
Standard input is empty
stdout
2.5