# Recursive definition of zero, one

**URL:** <https://discourse.julialang.org/t/recursive-definition-of-zero-one/80492>\
**Category:** General Usage\
**Created:** [May 4, 2022, 3:54pm UTC](https://discourse.julialang.org/t/recursive-definition-of-zero-one/80492 "2022-05-04T15:54:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![shiroghost](https://avatars.discourse-cdn.com/v4/letter/s/b9e5f3/32.png) [@shiroghost](https://discourse.julialang.org/u/shiroghost)\
**Post date:** [May 4, 2022, 3:54pm UTC](https://discourse.julialang.org/t/recursive-definition-of-zero-one/80492/1 "2022-05-04T15:54:16Z")

</div>

Hi all,

Imagine I have a data type like:

```julia
struct foo{T,N}
  c::NTuple{N,T}
end

```

and I want to define the zero function

```julia
import Base.zero
zero(s::foo{T,N}) where {T,N} = foo{T,N}(ntuple(i -> zero(T), N))

```

This allows me to get, for example:

```julia
julia> s = foo((1.2,2.2))
foo{Float64, 2}((1.2, 2.2))

julia> zero(s)
foo{Float64, 2}((0.0, 0.0))

```

But if I try a recursive definition, this fails:

```julia
julia> ss = foo((s,s))
foo{foo{Float64, 2}, 2}((foo{Float64, 2}((1.2, 2.2)), foo{Float64, 2}((1.2, 2.2))))

julia> zero(ss)
ERROR: MethodError: no method matching zero(::Type{foo{Float64, 2}})
Closest candidates are:
  zero(::Union{Type{P}, P}) where P<:Dates.Period at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.6/Dates/src/periods.jl:53
  zero(::foo{T, N}) where {T, N} at REPL[3]:1
  zero(::SparseArrays.AbstractSparseArray) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.6/SparseArrays/src/SparseArrays.jl:55
  ...

```

I do not understand why it fails. `zero(foo{Float64,2})` is perfectly well defined in terms of `zero(Float64)`.

Many thanks!

---

<div class="post-metadata">

**Author:** ![Sukera](https://avatars.discourse-cdn.com/v4/letter/s/ce7236/32.png) [@Sukera](https://discourse.julialang.org/u/Sukera)\
**Post date:** [May 4, 2022, 4:02pm UTC](https://discourse.julialang.org/t/recursive-definition-of-zero-one/80492/2 "2022-05-04T16:02:49Z")

</div>

It’s because you haven’t defined `zero(::Type{foo})`, but only `zero(::foo)` instead:

```julia
julia> Base.zero(::Type{foo{T,N}}) where {T,N} = foo{T,N}(ntuple(i -> zero(T), N))

julia> zero(ss)
foo{foo{Float64, 2}, 2}((foo{Float64, 2}((0.0, 0.0)), foo{Float64, 2}((0.0, 0.0))))

```

Your naive recursive definition falls back to calling `zero` on the _type_ `foo{Float64, 2}` and not its instance.
