Finding Position of Element in an Array

I do have to account for nothing so I have some crazy code which looks like this:

first(something(findfirst("multipart/form-data", get(headers, "Content-Type", "")), 0:-1)) != 0

It looks like returning -1 would make the check simpler. Although I do agree that it’s inconsistent with the way Julia represents nullable values (as a Union{Something,Nothing}).

In what? When will nothing be a valid key (not value)?

1 Like

Sorry, I think I’m missing your point. Probably my fault as I frankly can’t compute that code in my head. It’s an actual example of a complex sequence of find* and something. If I’m using them wrong and the code can be refactored, my apologies. Otherwise, I wish there was a simpler way, that snippet is painful to reason about.

Is the following what you are trying to do?

julia> headers = Dict("Content-Type" => "multipart/form-data; boundary=something")
Dict{String,String} with 1 entry:
  "Content-Type" => "multipart/form-data; boundary=something"

julia> first(something(findfirst("multipart/form-data", get(headers, "Content-Type", "")), 0:-1)) != 0
true

julia> occursin("multipart/form-data", get(headers, "Content-Type", ""))
true
1 Like

As far as I can tell, the solution @kristoffer.carlsson is referring to and what you are looking for works like this:

res = findfirst("multipart/form-data", get(headers, "Content-Type", ""))
if !isnothing(res) #alternatively use !==nothing
  println("Found at $res !!")
else
  println("Darn, no such field...")
end

find* returns Union{Nothing,T} and as long as nothing is not a valid value for T you can simply check for it as in the example I gave, to find out if an occurence was found.
If nothing is a valid value for T on the other hand, then you need to encapsulate the values of T (like with something(.)) and thus make the new type again distinguishable from Nothing.

Oh, that’s pretty :heart_eyes:

I refactored the logic from

searchindex(get(headers, "Content-Type", ""), "application/x-www-form-urlencoded") != 0

when searchindex was deprecated and ended up with that monstrosity.

that now just became firstindex(...) !== nothing :smiley:

The whole logic now works in fact like the iteration protocol in that it uses the relevant type when found and nothing when not found/at end. This works that smooth thanks to some optimizations in the compiler. And the “new” iteration protocol is very smooth in my opinion ^^

3 Likes