Open azjezz opened 1 year ago
@veewee what do you think about this? could be really useful for chaining :)
Dict\get($arr, "foo")
->then(fn($value) => ...)
->then(fn($value) => ...)
->then(fn($value) => ...);
would be lovely indeed! The typed one would throw a coerce exception? Is that intended?
Where do you draw the line in consistency? Since other functions currently return nullables?
In an ideal world, we wouldnt have to deal with nulls in PSL...
hm, returning none for invalid type would be a weird, and might be confusing, i think we can start by adding get
and leave get_typed
for later.
The typed version could return Option<Result<T>>
But then again: where do we draw the line in consistent return types in PSL...
I think there's a solution, we use naming to indicate what the return will be.
Psl\Collection
s have a method named at($k)
which throws if $k
is not found, and get($k)
which returns T|null
, we can keep this behavior and introduce a new name for return Option<T>
, but, we must implement these 3 functions for all Psl\Collection
, Psl\Vec
, and Psl\Dict
to stay consistent.
rule:
at($k): T
-> return T
if $k
exists, throw if $k
doesn't existget($k): T|null
-> return T
if $k
exists, null if $k
doesn't exist.acquire($k): Option<T>
-> return Some(T)
if $k
exists, None
if $k
doesn't exist. acquire
is not the best name out there, but that's what i have in mind right now, if you can think of something better, you can tell me :P
as for _typed
, we should also introduce a rule for this, which would mean we deprecate Json\typed
and introduce Json\decode_typed
.
and it's a simple rule:
_typed
are used for extracting a value for the given argument in a typed manner, they all have a generic template named T
, they all take $type
argument of type Type\TypeInterface<T>
as their last argument, and return either T
or another generic type containing T
, these functions will always throw Type\Exception\ExceptionInterface
.now as for acquire_typed($k): Option<T>
, you can simply wrap it in a result like this:
Result\wrap(fn() => Dict\acquire_typed($arr, $k, $type))
->then(function($option) {
})
->catch(function($type_error) {
});
Yeah that sounds good. I don't hate acquire
tbh
Some possible alternatives - don't have one I really like atm:
find
is a no-go for me, Vec\find($list, $x)
makes me think it's searching for an entry using $x
.
try
is also a no-go, this conflicts with the undocumented async convention ( see IO\ReadHandleInterface::read()
vs IO\ReadHandleInterface::tryRead()
, IO\WriteHandleInterface::write()
vs IO\WriteHandleInterface::tryWrite()
,
Channel\SenderInterface::send()
vs Channel\SenderInterface::trySend()
, and more. )
( there's also lock() vs tryLock(), it's more of a waiting convention, if x()
might wait, there must be tryX()
which doesn't wait )
Hm yeah aqcuire is one of the betters. Some synonyms, maybe you see one you likke better :)
API: