Vincent
Vincent

Reputation: 1371

Julia assignment to Nullable Node

I am trying to assign a value to a Nullable Node. To make the code more readable, I wrote a getter function. Upon using the getter function to assign a value to a node, it doesn't work. Any ideas why?

Here is the code:

type Node
    data
    left::Nullable{Node}
    right::Nullable{Node}

    Node() = (x = new(); x.left = Nullable{Node}(); x.right = Nullable{Node}(); x)
    Node(data) = (x = new(); x.data = data; x.left = Nullable{Node}(); x.right = Nullable{Node}(); x)
end

# Helper function to return the left node
getLeft(n::Node) = n.left

n = Node(1)
# This is what I would like to have, however it returns
# "getLeft":
getLeft(n) = Node(-1)

# what works is to write:
n.left = Node(-1)

Of course I also tried to write:

function getLeft(n::TreeNode)
    return n.left
end

which does not make any difference.

I don't understand why the "getLeft" function does not allow assignment, even though it return "n.left", and direct assignment to "n.left" works.

Upvotes: 1

Views: 73

Answers (1)

Gauthier Soleilhac
Gauthier Soleilhac

Reputation: 386

The line getLeft(n) = Node(-1)creates a new function that can be compiled for any type other than Node (because you wrote a more specific function for the type node : getLeft(n::Node) = n.left
That's why you should see getLeft (generic function with 2 methods) if you type your code in the REPL

You might be tempted to write

left = getLeft(n)
left = Node(-1)

But that wouldn't work either, the first line creates an alias, left, for the object pointed to by n.left
Then the second line creates a Node and reassigns the alias left to that node, neither n or n.left are modified

What you could do is write a function to assign a left node e.g.

function setLeft!(n, l)
    n.left = l
end

> setLeft!(n, Node(-1))

But you might prefer to stick with assigning n.left directly

Upvotes: 2

Related Questions