# Is there a built-in function for the natural length of a segment represented by an iterator?

**URL:** <https://discourse.julialang.org/t/is-there-a-built-in-function-for-the-natural-length-of-a-segment-represented-by-an-iterator/112414>\
**Category:** New to Julia\
**Tags:** question\
**Created:** [April 2, 2024, 11:44am UTC](https://discourse.julialang.org/t/is-there-a-built-in-function-for-the-natural-length-of-a-segment-represented-by-an-iterator/112414 "2024-04-02T11:44:40Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [April 2, 2024, 1:52pm UTC](https://discourse.julialang.org/t/is-there-a-built-in-function-for-the-natural-length-of-a-segment-represented-by-an-iterator/112414/8 "2024-04-02T13:52:38Z")

</div>

> [@mkitti](#):
>
> This does not work for all iterators.

Even `last(a) - first(a)` seems wrong to me for a non-sorted iterator. A more general solution would be to use the [`extrema` function](https://docs.julialang.org/en/v1/base/collections/#Base.extrema):

```julia
diameter(itr) = -(reverse(extrema(itr))...)

```

which is equivalent to the more verbose (but more readable) implementation:

```julia
function diameter(itr)
    min, max = extrema(itr)
    return max - min
end

```

(This requires looping over the entire iterator in general, though for a range there is an optimized `extrema` method that just looks at the endpoints.)

`extrema` is quite a useful function (which takes some effort to implement well), and provides strictly more information than `diameter`. So, I don’t think there is much need for a built-in (or package) function to compute `diameter`, since computing `diameter` is a one-liner given `extrema`.

---

_[View the full topic](https://discourse.julialang.org/t/is-there-a-built-in-function-for-the-natural-length-of-a-segment-represented-by-an-iterator/112414)._
