In packages and platforms, there are cases like below where results should always be Ok something
, but as code is edited over time you can definitely screw things up. This makes me wonder if it's not better to crash in cases like this, thereby making it a lot easier to notice when it did get screwed up.
if isValidUtf8Byte byte then
Str.toUtf8 string
|> List.append byte
|> Str.fromUtf8
|> Result.withDefault "" # This will never fail
If it should truly be impossible, never use a default
Crash or return an error tag anyways. That's my opinion.
That said, your function above should probably be rewritten
when Str.toUtf8 string |> List.append byte |> Str.fromUtf8 is
Ok str -> str
Err _ -> -- do whatever the false case of the if expression above does
Actually, after writing this out, I am not 100% sure this should be written this way. It will be slower on the error case.
So I would say, for this example, due to perf reasons, probably should just stay the same as the original code but crash.
Aside, crashing should actually optimize better than using a default.
Surely it doesn't matter if it's slow in the error case, when that's never expected to happen?
Perhaps for the case of a missed branch prediction?
when that's never expected to happen?
I'm not sure that's the case here, the else
branch was omitted.
Str.fromUtf8
will never fail if we checked the byte was valid.
By changing to the code I shared above, the Err _
would match the else
branch that we don't see in the above code. So it does not match the # This will never fail
part of the code.
@Anton is this just for Url.roc or is it used elsewhere?
This is indeed just for Url.roc
Then we have a separate solution for the full function that already was applied to basic CLI. So should be good.
Last updated: Jul 06 2025 at 12:14 UTC