tov / dssl2

A data structures student language, version 2
MIT License
9 stars 5 forks source link

Hard to define recursive contracts/structs #3

Open tov opened 7 years ago

tov commented 7 years ago

This code works:

    defstruct Node(
       prev: MaybeC(Node?),
       data: MaybeC(X),
       next: MaybeC(Node?))

But this code doesn't:

    defstruct Node(
       prev: Link,
       data: MaybeC(X),
       next: Link)
    let Link = MaybeC(Node?)

It fails, saying that Link is undefined.

tov commented 7 years ago

But now this code works:

let Link = MaybeC(Node?)
defstruct Node(
       prev: Link,
       data: MaybeC(X),
       next: Link)

The order matters. It shouldn't, but it's what we have now.

tov commented 5 years ago

Update:

#lang dssl2

def MaybeC(c): OrC(c, NoneC)

let IntLink = MaybeC(IntNode?)
struct IntNode:
    let prev: IntLink
    let data: int?
    let next: IntLink

class _Node[T]:
    let _prev: _Link(T)
    let _data: MaybeC(T)
    let _next: _Link(T)

    def __init__(self):
        self._prev = None
        self._data = None
        self._next = None

    def prev(self): self._prev
    def data(self): self._data
    def next(self): self._next
    def set_prev(self, v): self._prev = v
    def set_data(self, v): self._data = v
    def set_next(self, v): self._next = v

def _Link(T): MaybeC(_Node?[T])

let n = _Node[int?]()

assert n.data() is None
n.set_data(5)
assert n.data() == 5
assert_error n.set_data('hello')
assert n.data() == 5

assert n.next() is None
n.set_next(n)
assert n.next() is n
n.set_next(None)
assert n.next() is None