質問

I'm relatively new at Scala and I'm struggling with DSLs. Currently I'm trying to implement a simple Math DSL which could be used with some kind of natural language.

My Idea:

print(Calculate 4 plus 6)=> returns 10

print(Calculate 4 mins 2)=> returns 2 ... and so on

So far I have implemented two classes. The main class which serves just for calling the method and a calculation class. My Problem is a have no Idea how I could pass the first number to the calculation object, because It is not allowed to define parameters.

Could Anyone Help with an example or something?

役に立ちましたか?

解決

You are going to run into some troubles making this feel like a natural language since the natural form that Scala wants to parse is class-instance method argument method argument method argument ..., which is rather unlike English.

However, here is a framework to get you started, with lots of extra boilerplate syntax to make the parsing work out right.

object Now {
  class Value(val please: Double) {
    def plus(d: Double) = new Value(please + d)
    def minus(d: Double) = new Value(please - d)
    override def toString = please.toString
  }
  def calculate(d: Double): Value = new Value(d)
}

And here it is working (after an import language.postfixOps):

scala> Now calculate 4 plus 6 please
res1: Double = 10.0

Incidentally, there's already a very good natural way to ask for 4+6...it's 4+6. It works for speakers of many different languages, and for almost all computer languages too. So this DSL might be fun for a toy, but I'm not sure what the practical utility is.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top