Search code examples
scalatypesrecursive-datastructuresquine

Establishing quine type in scala


I have to parse a string with syntax

lazy val expr: Parser[Term ~ Option[<recursion>]] = term ~ opt(expr)

You see, it uses itself to parse subexpressions. But what does this type result in? In order to reproduce the problem, I created a somewhat similar problem

def quine(depth: Int, result: (Any, Option[Any])): (Any, Option[Any]) = 
    if (depth == 0) result else {quine(depth - 1, (depth, Some(result)))}
quine(5, (true, None))

As you see, I used Any since I do not know how to give exact type.

The lists somehow define proto type List[A], extended by Cons[A](head: A, tail: List[A]) and some magic Nil. This allows the list to recur somehow. But, what should I do in my case?


Solution

  • I am not sure what you are trying to do here, because your result type is different between the function definition and invocation (the first element is Int in the former and Boolean in the latter, that can't work).

    But, provided that was just a typo, something like this should do the trick:

     case class Quine(n: Int, q: Option[Quine])
     def quine(depth: Int, result: Quine): Quine =  
      if (depth == 0) result else 
        quine(depth - 1, Quine(depth, Some(result)))
    
     quine(5, Quine(6, None))