Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call the more general method from a specific one

Tags:

julia

I am trying to call a general method from a specific one, but cannot figure out how.

function fn(x)
  # generic
  ...
end

function fn(x :: String)
  # I want to call the generic version here
  val = fn(x)
  # do something with val and then return it
  ...
end

Is this possible?

A workaround is using a helper function that can be called from both generic and specific methods. e.g.

function helper(x)
  # main work is here
  ...
end

function fn(x)
  # generic
  helper(x)
end

function fn(x :: String)
  val = helper(x)
  # now use the val to do something
  ...
end

Without using such helpers, is there a way to control the dispatch to select a particular method to use? Is there something like :before and :after keywords and call-next-method from lisp CLOS in Julia?

like image 338
rajashekar Avatar asked Dec 14 '20 12:12

rajashekar


1 Answers

You can use the invoke function:

julia> function fn(x)
         @info "generic $x"
       end
fn (generic function with 1 method)

julia> function fn(x :: String)
         @info "before"
         invoke(fn, Tuple{Any}, x)
         @info "after"
       end
fn (generic function with 2 methods)

julia> fn(10)
[ Info: generic 10

julia> fn("10")
[ Info: before
[ Info: generic 10
[ Info: after

(just to be clear - the printing of "before" and "after" is only to highlight what gets executed in what sequence - the only thing that is related to method dispatch here is the invoke function)

like image 189
Bogumił Kamiński Avatar answered Oct 19 '22 00:10

Bogumił Kamiński