using constructor to compute new field


#1

Hi - The following does not create a Ray object and says “no method matching Ray(::Point{Float64}, ::Point{Float64})”. Does anyone have a solution? Many thanks.

immutable Point{T<:AbstractFloat}
x::T
y::T
z::T
end

immutable Ray{P<:Point{AbstractFloat}, T<:AbstractFloat}
v1::stuck_out_tongue:
v2::stuck_out_tongue:

dx::T
dy::T
dz::T
function Ray{P}(v1::P, v2::P) where P<:Point{AbstractFloat}
    dx = v2.x - v1.x
    dy = v2.y - v1.y
    dz = v2.z - v1.z
    dx2 = dx * dx
    dy2 = dy * dy
    dz2 = dz * dz
    s = dx2 + dy2 + dz2
    l = sqrt(s)
    dx = dx / l
    dy = dy / l
    dz = dz / l
    new{P, T}(v1, v2, dx, dy, dz)
end

end

p1 = Point(1.0, 2.0, 3.3)
p2 = Point(4.0, 3.0, 5.5)
r = Ray(p1, p2)


#2

:stuck_out_tongue:” is not a valid type definition :smile: .

Joking aside… This works:

julia> immutable Ray{P<:Point, T<:AbstractFloat}
       v1::P
       v2::P
       dx::T
       dy::T
       dz::T
       function Ray(v1::P, v2::P) where {T,P<:Point{T}}
           dx = v2.x - v1.x
           dy = v2.y - v1.y
           dz = v2.z - v1.z
           dx2 = dx * dx
           dy2 = dy * dy
           dz2 = dz * dz
           s = dx2 + dy2 + dz2
           l = sqrt(s)
           dx = dx / l
           dy = dy / l
           dz = dz / l
           new{P, T}(v1, v2, dx, dy, dz)
       end
       end
julia> p1 = Point(1.0, 2.0, 3.3)
Point{Float64}(1.0, 2.0, 3.3)

julia> p2 = Point(4.0, 3.0, 5.5)
Point{Float64}(4.0, 3.0, 5.5)

julia> r = Ray(p1, p2)
Ray{Point{Float64},Float64}(Point{Float64}(1.0, 2.0, 3.3), Point{Float64}(4.0, 3.0, 5.5), 0.7787611974767475, 0.2595870658255825, 0.5710915448162815)

Also, here is a post explaining how to properly quote your codes here at discourse forum