1

I have a simple abstract data type, a tree.

sealed trait Tree[A]
case object EmptyTree extends Tree[Nothing]
case class Leaf[A](value: A) extends Tree[A]
case class Node[A](op: A => A, branches: List[Tree[A]]) extends Tree[A]

How can i make the operation that a Node holds to accept a variable length number of arguments of type A?

An exemple:

def printAll(strings: String*) {
  strings.foreach(println)
}

printAll receives a variable number of strings.

In the same way i wanted to make my Tree to hold an operation op of the type A* => A.

A possible way would be to make it receive a List[A], but i wonder if there isn't a more direct way of doing this.


by the way can i also turn branches: List[Tree[A]] into something like branches: Tree[A]*. Does this make sense from a design perspective?

1 Answer 1

3

You can use Seq in the signature, then you will be able to pass varargs functions

sealed trait Tree[A]
case object EmptyTree extends Tree[Nothing]
case class Leaf[A](value: A) extends Tree[A]
case class Node[A](op: Seq[A] => A, branches: List[Tree[A]]) extends Tree[A]

object Test {
  Node[String](test[String], List())

  def test[A](elem: A*): A = ???
}
Sign up to request clarification or add additional context in comments.

3 Comments

going to test it, it makes sense, than you for your answer
by the way, can i also make branches: List[Tree[A]]) like branches: Tree[A]*. Does this make sense from a design perspective?
The varargs makes sense when you want to have a function that accepts n elements as parameter, but it makes less sense when you are declaring the fields of a class. But it's up to you to use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.