Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed ADT example in DOCS.md #854

Closed
wants to merge 1 commit into from
Closed

Fixed ADT example in DOCS.md #854

wants to merge 1 commit into from

Conversation

joangq
Copy link

@joangq joangq commented Oct 18, 2024

The example as it is runs and compiles, but the functionality is wrong.
With the original formulation, the output is:

0
0
0

While it should've been:

0
1
3

This is because the cases in the depth function are using the constructor of Tree instead of the ones defined as data.
Changing the pattern matching to the correct constructors fixes the behaviour.

@evhub evhub added this to the v3.1.3 milestone Oct 18, 2024
evhub added a commit that referenced this pull request Oct 20, 2024
Resolves   #854.
@evhub
Copy link
Owner

evhub commented Oct 20, 2024

Ah, this is an interesting case. There's actually a bunch of ways to resolve this. The basic issue is that you need to make sure that Coconut does data matching here rather than class matching. But you can accomplish that in a bunch of different ways:

This is probably what the docs should show:

data Tree
data Empty() from Tree
data Leaf(n) from Tree
data Node(l, r) from Tree

case def depth:
    case(Tree()) = 0
    case(Tree(n)) = 1
    case(Tree(l, r)) = 1 + max(depth(l), depth(r))

This also works if you want to be very explicit:

class Tree
data Empty() from Tree
data Leaf(n) from Tree
data Node(l, r) from Tree

case def depth:
    case(data Tree()) = 0
    case(data Tree(n)) = 1
    case(data Tree(l, r)) = 1 + max(depth(l), depth(r))

@evhub evhub closed this Oct 20, 2024
@evhub evhub added the resolved label Oct 20, 2024
@joangq joangq deleted the patch-1 branch October 20, 2024 14:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants