Skip to content

Commit 373ed4d

Browse files
committed
Update
1 parent 6fde3dc commit 373ed4d

File tree

2 files changed

+8
-25
lines changed

2 files changed

+8
-25
lines changed

src/ndsparsearray.jl

Lines changed: 7 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -521,14 +521,8 @@ More efficient than `A = A + scalar`.
521521
Works with any type that supports addition with the array's element type.
522522
"""
523523
function add!(A::NDSparseArray{T}, scalar) where {T}
524-
# For generic types, we can't assume zero() exists, so we try to check if it's zero
525-
# For most numeric types this will work, for others we'll skip the check
526-
try
527-
if scalar == zero(typeof(scalar))
528-
return A
529-
end
530-
catch MethodError
531-
# zero() not defined for this type, continue with the operation
524+
if iszero(scalar)
525+
return A
532526
end
533527

534528
# Add scalar to all stored values, converting to A's type
@@ -581,14 +575,8 @@ More efficient than `A = A - scalar`.
581575
Works with any type that supports subtraction with the array's element type.
582576
"""
583577
function sub!(A::NDSparseArray{T}, scalar) where {T}
584-
# For generic types, we can't assume zero() exists, so we try to check if it's zero
585-
# For most numeric types this will work, for others we'll skip the check
586-
try
587-
if scalar == zero(typeof(scalar))
588-
return A
589-
end
590-
catch MethodError
591-
# zero() not defined for this type, continue with the operation
578+
if iszero(scalar)
579+
return A
592580
end
593581

594582
# Subtract scalar from all stored values, converting to A's type
@@ -608,15 +596,9 @@ More efficient than `A = A * scalar`.
608596
Works with any type that supports multiplication with the array's element type.
609597
"""
610598
function mul!(A::NDSparseArray{T}, scalar) where {T}
611-
# For generic types, we can't assume zero() or one() exist, so we try to check
612-
# For most numeric types this will work, for others we'll skip the check
613-
try
614-
if scalar == zero(typeof(scalar))
615-
empty!(A.data)
616-
return A
617-
end
618-
catch MethodError
619-
# zero() not defined for this type, continue
599+
if iszero(scalar)
600+
empty!(A.data)
601+
return A
620602
end
621603

622604
try

test/test_inplace_operations.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,7 @@ using Test
352352
Base.:-(a::CustomNumber, b::CustomNumber) = CustomNumber(a.value - b.value)
353353
Base.:*(a::CustomNumber, b::CustomNumber) = CustomNumber(a.value * b.value)
354354
Base.convert(::Type{CustomNumber}, x::CustomNumber) = x
355+
Base.zero(::Type{CustomNumber}) = CustomNumber(0.0)
355356

356357
A = NDSparseArray{CustomNumber, 2}((2, 2))
357358
A[1, 1] = CustomNumber(5.0)

0 commit comments

Comments
 (0)