Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a method to an existing function in Julia?

Tags:

methods

julia

So within Julia, every function has methods.

The following makes sense:

f(x, y) = x + y
f(x) = x + 2

This provides two methods attached to this function.

But let's say I want to add a method to an existing Julia function, instead of overriding it.

For example:

a = [2, 3]
push!(a, 4)
a == [2, 3, 4] # true

type Node
   children :: Array{Node}
end

function push!(base :: Node, child :: Node)
   push!(base.children, child)
end

This is what I want to do; extend existing functions to act appropriately with new types. But this throws an error. Is this possible?

like image 593
Kites Avatar asked Mar 20 '15 02:03

Kites


1 Answers

I just solved it, so I thought to still post the question, in case people have trouble in the future.

You have to explicitly import a function in order to extend it.

So this would work:

import Base.push!

function push!(base :: Node, child :: Node)
   push!(base.children, child)
end
like image 154
Kites Avatar answered Oct 27 '22 23:10

Kites