2

I want to create simple DSL to declare trees:

  1
 / \
2   3
   /|\
  4 5 6

The DSL should look something like:

val node = Node(1) {
  Node(2),
  Node(3) {
    Node(4),
    Node(5),
    Node(6)
  }
}

This is what I reached so far:

case class Node(id: Int, childNodes: List[Node] = Nil) {
  def apply(nodes: Node*): Node = copy(childNodes = nodes.toList)
}

However, the declaration of tree above does not compile. It says:

';' expected but ',' found

If I change curly braces to parentheses, it works:

val node = Node(1) (
  Node(2),
  Node(3) (
    Node(4),
    Node(5),
    Node(6)
  )
)

But I think it is a bit more intuitive to use curly braces because they resemble hierarchical declaration of classes in OOP.

Any recommendations to make it work? Changing the DSL is also allowable (this syntax is not strict, this is just what came to my mind).

ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
  • `{ Node(4), Node(5), Node(6) }` - such syntax doesn't mean anything in Scala, it's plain incorrect. – ghik Oct 10 '13 at 21:52
  • Just stick with the parenthesis and you might find useful to read this: http://stackoverflow.com/questions/4386127/what-is-the-formal-difference-in-scala-between-braces-and-parentheses-and-when – Vinicius Miana Oct 11 '13 at 01:45

1 Answers1

0

How about something like that :

object Foo {
  case class Node(id: Int, childNodes: List[Node] = Nil) {
    def apply(nodes: List[Node]): Node = copy(childNodes = nodes)
  }
}

object Conv {
  implicit def toList(n: Foo.Node) : List[Foo.Node] = List(n)
}

So that you can do this :

import Conv._
val node = Node(1) {
  Node(2) :: Node(3) { Node(4) }
}
itsu
  • 222
  • 1
  • 10