Julia: argument défaut de type conditionnel — Les-mathematiques.net The most powerful custom community solution in the world

Julia: argument défaut de type conditionnel

Bonjour. Voilà ma fonction:
function hypergeom(
        m::Integer,
        a::Vector{T},
        b::Vector{T},
        x::T,
        alpha::R=nothing
    ) where {R<:Real, T<:Union{R,Complex{R}}}
    if isnothing(alpha)
        alpha = R(1)
    end
    return hypergeomI(m, alpha, a, b, 1, x)
end
Le truc, c'est que je veux alpha=1 par défaut. Mais si R est Float64, il me faut un alpha en Float64, tandis que si R est Rational, il me faut un alpha en Rational.

Ce code marche. Mais est-ce une bonne manière de procéder ?

Réponses

  • Je ne comprends plus rien. J'ai une fonction similaire, la différence est que x est un vecteur ici:
    function hypergeom(
            m::Integer,
            a::Vector{T},
            b::Vector{T},
            x::Vector{T},
            alpha::R=nothing
        ) where {R<:Real, T<:Union{R,Complex{R}}}
        if isnothing(alpha)
            alpha = R(2)
        end
        .......
    
    Et ici, ça ne marche pas quand je ne spécifie pas alpha.
  • Ah non, le 1er code ne marche pas non plus. Ça marchait parce que j'avais d'abord fait
    alpha::nothing
    
    puis j'ai changé en
    alpha::R=nothing
    
    Julia a gardé les deux méthodes et la 1ère marche. Donc le code qui marche est:
    function hypergeom(
            m::Integer,
            a::Vector{T},
            b::Vector{T},
            x::T,
            alpha=nothing
        ) where {R<:Real, T<:Union{R,Complex{R}}}
        if isnothing(alpha)
            alpha = R(1)
        end
        return hypergeomI(m, alpha, a, b, 1, x)
    end
    
    Même question: est-ce une bonne façon de procéder ? Je vais faire plus de tests car j'ai des doutes...
  • On a l'impression que les lignes Vector ne permettent pas de récupérer le type, caché à l'intérieur du tableau.
    Que se passe-t-il si, dans ton code qui fonctionne, tu inverses la ligne de x et celle de b ?
  • Non je ne pense pas que ce soit ça. C'est le alpha::R=nothing qui engendrait l'erreur.

    Maintenant je fais alpha::Union{Nothing,R}=nothing (car le alpha=nothing n'est pas assez typé à mon goût).
Connectez-vous ou Inscrivez-vous pour répondre.
Success message!