# Getting first element of a possibly empty Eduction (Transducers.jl)

**URL:** <https://discourse.julialang.org/t/getting-first-element-of-a-possibly-empty-eduction-transducers-jl/86932>\
**Category:** General Usage\
**Tags:** transducers\
**Created:** [September 8, 2022, 9:54am UTC](https://discourse.julialang.org/t/getting-first-element-of-a-possibly-empty-eduction-transducers-jl/86932 "2022-09-08T09:54:17Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![josuagrw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/josuagrw/32/1015_2.png) [@josuagrw](https://discourse.julialang.org/u/josuagrw)\
**Post date:** [September 8, 2022, 9:54am UTC](https://discourse.julialang.org/t/getting-first-element-of-a-possibly-empty-eduction-transducers-jl/86932/1 "2022-09-08T09:54:17Z")

</div>

Consider the following eduction

```julia

julia> using Transducers

julia> ed = (rand() for i in 1:10) |> Filter(<(0.1))
Base.Generator{UnitRange{Int64}, var"#1#2"} |>
    Filter(Fix2)

```

Getting the first element is tricky because it might not exist

```julia
julia> ed |> first
ERROR: ArgumentError: collection must be non-empty
Stacktrace:
 [1] first
   @ ./abstractarray.jl:419 [inlined]
 [2] |>(x::Transducers.Eduction{Transducers.Reduction{Filter{Base.Fix2{typeof(<), Float64}}, Transducers.BottomRF{Completing{typeof(push!!)}}}, Base.Generator{UnitRange{Int64}, var"#1#2"}}, f::typeof(first))
   @ Base ./operators.jl:966
 [3] top-level scope
   @ REPL[3]:1

```

I came across a nice way to avoid the exception and get a `nothing` instead (if `ed` is empty):

```julia
julia> ed |> Take(1) |> foldxl(something, init = nothing)
0.060629047515483814

julia> ed |> Take(1) |> foldxl(something, init = nothing)
0.06279752181624232

julia> ed |> Take(1) |> foldxl(something, init = nothing)

```

(The last case returned a `nothing` which is not displayed in REPL.)

Hope it helps folks. (Note that `findfirst` can be a lot faster when it is applicable. This is an MWE not a real usecase.)
