Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: Constructor Embedding a function inside a type

Tags:

oop

julia

I am new to OOP. Lets say I have a Type and function like this:

   type Person
      name::String
      male::Bool
      age::Float64
      children::Int

    end

    function describe(p::Person)
      println("Name: ", p.name, " Male: ", p.male)
      println("Age: ", p.age, " Children: ", p.children)
    end


    ted = Person("Ted",1,55,0)

    describe(ted)

Is there a way to have the describe function embedded inside the type. For example if I input something like this

ted.describe()

I would get:

Name Ted Male true
Age 55.0 Children 0
like image 299
ccsv Avatar asked Nov 07 '14 11:11

ccsv


2 Answers

I'm new to Julia too, and had the same request some times ago.

Now I'd solve your problem with the following code, thank to the help from
 Understanding object-oriented programming in Julia – Objects-part 1 ,

I know that an anonymous fonction are not very fast, but I think the overhead is not too bad for a "printing" function.

#!/usr/bin/env julia
mutable struct Person
    name::AbstractString
    male::Bool
    age::Float64
    children::Int
    describe::Function
    function Person(name,male,age,children)
        this = new()
        this.name = name
        this.male = male
        this.age = age
        this.children = children
        # anonymous functions are not known to be fast ;-)
        this.describe =  function() describe(this) end
        this
    end
end

function describe(p::Person)
    println("Name: ", p.name, " Male: ", p.male)
    println("Age: ", p.age, " Children: ", p.children)
end

ted = Person("Ted",1,55,0)
# describe(ted)
ted.describe()

However as 0xMB said: it's not the Julia way. But I like the method chaining call system from Ruby, So I hope a syntactical sugger will appear some day to be able to easily create some alias to create such a "member function".

-- Maurice

like image 196
diam Avatar answered Sep 30 '22 13:09

diam


Julia does not support this dot notation. This may differ from other object oriented languages where methods are part of your objects but in Julia function are considered to act on data in general and are therefore not defined inside your objects data.

Your example is just fine.

like image 30
0xMB Avatar answered Sep 30 '22 13:09

0xMB