From 8a460f08053e5eafaf1b513154c30cc433064b05 Mon Sep 17 00:00:00 2001 From: Beforerr Date: Sat, 16 Nov 2024 15:48:07 -0800 Subject: [PATCH] feat: inner constructor for Particle --- docs/src/api.md | 1 - docs/src/index.md | 8 ++++---- src/types.jl | 11 +++++++++-- test/types.jl | 9 +++++++++ 4 files changed, 22 insertions(+), 7 deletions(-) diff --git a/docs/src/api.md b/docs/src/api.md index 2e869e5..d0b89f1 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -11,7 +11,6 @@ Order = [:type] ## Constructors ```@docs -Particle proton electron ``` diff --git a/docs/src/index.md b/docs/src/index.md index 92a33c7..6c07440 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -35,15 +35,15 @@ p = proton() # proton α = Particle("alpha") # alpha particle # Create ions and isotopes -fe3 = Particle("Fe3+") # Iron(III) ion -fe56 = Particle("Fe-56") # Iron-56 +fe = Particle("Fe-56 3+") # Iron(III) ion +fe54 = Particle(:Fe, 3, 54) d = Particle("D+") # Deuteron # Access properties println("Electron mass: ", mass(e)) println("Alpha particle charge: ", charge(α)) -println("Iron charge: ", charge(fe3)) -println("Iron-56 mass number: ", mass_number(fe56)) +println("Iron(III) ion charge: ", charge(fe)) +println("Iron-54 mass number: ", mass_number(fe54)) println("Deuteron mass: ", mass(d)) ``` diff --git a/src/types.jl b/src/types.jl index a326ff9..0358dea 100644 --- a/src/types.jl +++ b/src/types.jl @@ -18,7 +18,7 @@ Implementation type for charged particles. # Fields - `symbol::Symbol`: Chemical symbol or particle identifier (e.g., :Fe, :e, :μ) - `charge_number::Int`: Number of elementary charges (can be negative) -- `mass_number::Int`: Total number of nucleons (protons + neutrons) +- `mass_number::Int`: Total number of nucleons (protons + neutrons). If not provided, defaults to the most common isotope mass number # Notes - Mass number : For elementary particles like electrons and muons, `mass_number` is 0 @@ -35,7 +35,14 @@ struct Particle <: AbstractParticle symbol::Symbol charge_number::Int mass_number::Int - + function Particle(symbol, charge_number, mass_number=nothing) + if isnothing(mass_number) + mass_number = elements[symbol].mass_number + else + mass_number >= 0 || throw(ArgumentError("Mass number must be non-negative, got $mass_number")) + end + new(symbol, charge_number, mass_number) + end end """ diff --git a/test/types.jl b/test/types.jl index 665257e..d610e73 100644 --- a/test/types.jl +++ b/test/types.jl @@ -1,6 +1,15 @@ using Test, ChargedParticles, Unitful +using ChargedParticles: is_electron, is_proton using Unitful: q +@testset "Constructor" begin + # Test invalid mass numbers + @test_throws ArgumentError Particle(:He, 2, -1) + + # Default mass number + @test mass_number(Particle(:He, 2)) == 4 +end + @testset "String Constructor" begin # Test common aliases @test is_electron(Particle("electron"))