Extend a bunch of functions within (sub)modules – best practice


#1

Lets say I defined a new abstract datatype and have a few functions and algorithms to run. Here’s a sketch of my code

module A
import Base.norm, Base.length
export norm, length, AType
abstract AType
function norm(a:AType,...) #some more parameters maybe
  error("Not available for your subtype");
end
function length(...)#again some parameters
  return norm(...)/2;
end
function alg1(a::Atype, b::aType)
  # Compute and return something maybe using norm and length
end
end # module A

And due to the error in the general norm there any subtype has to implement that (is there a nicer way to enforce implementation?)

module B
import A.norm, A.length
export norm, length #necessary? I think so...
export BType <: AType #subtype
function norm(b:BType)
  #implementation for b
end
# also extend length()...skipped for shortness
end #module B

I’m new to Julia so i’m not sure whether modules are the right way. My problem is, that i’m not having 2 functions like in the short example but let’s say 8 or 10, and maybe half of them stem from Base the others are introduces as norm in the „UberType“ module A.

As far as i got it working, any new type CType, DType, EType (getting its own module), has to import A.norm and all other (8-10) functions and export them to make the extension „publicly“ known.

Is there a nicer way to let a specification happen? I am sure, this idea here looks a lot like OOP, that’s where I’m coming from and maybe I’m thinking too much in these ideas.
I would like to avoid import/exporting all the functions just to extend them in every new module extending AType into another specification.

How can I achieve this?

Despite that I slowly like the way Julia works (though I haven’t gotten to the part where I can see performance, because I’m just starting).


#2

You probably use too many modules here. Modules in Julia generally don’t go per type nor per file, but per namespace convenience, to avoid conflicts when loading files which may use the same name with two different meanings. So you could place all subtypes of AType in the same module, even if they are placed in different files.


#3

This may be the easiest way to have catch-everything-that-falls-through versions of functions:


import Base: norm, length

function norm(xs...)
     signature = string( typeof(xs) )
     throw( ErrorException(" Not Implemented for $signature " ) )
end

function length(xs...)
    return norm(xs...)/2
end

#4

@akis thanks for the comment, as I said I’m still learning and maybe you’re right, I’ll change that

@jsarnoff that’s a neat falls-through – haven’t included the name of the type, where the implementation is missing yet.