letrec in Scala? (Immutable way to “Tie the knot?”)

后端 未结 1 1437
臣服心动
臣服心动 2021-02-20 05:19

Suppose I have a stupid little case class like so:

case class Foo(name: String, other: Foo)

How can I define a and b

相关标签:
1条回答
  • 2021-02-20 05:30

    You want Foo to be unchanged, but laziness in Scala is on the declaration site. It is impossible for Foo to be non-strict without changing it, and the pattern indicated in Haskell only works because Foo, there, is non-strict (that is, Foo "a" b doesn't evaluate b immediately).

    Otherwise the solution is pretty much the same, allowing for the hoops necessary to get everything non-strict:

    class Foo(name: String, other0: => Foo) { // Cannot be case class, because that mandates strictness
      lazy val other = other0 // otherwise Scala will always reevaluate
    }
    object Foo {
      def apply(name: String, other: => Foo) = new Foo(name, other)
    }
    
    val (a: Foo, b: Foo) = (Foo("a", b), Foo("b", a))
    
    0 讨论(0)
提交回复
热议问题