janet-lang / janet

A dynamic language and bytecode vm
https://janet-lang.org
MIT License
3.43k stars 221 forks source link

Add `lengthable?` #1279

Closed primo-ppcg closed 11 months ago

primo-ppcg commented 12 months ago

I've proposed this previously, and determined that it wasn't necessary, but it seems that it is.

JANET_TFLAG_LENGTHABLE is used within the capi to efficiently determine if a given Janet is a bytes, indexed, or dictionary - in other words, a vaild target for length. Many functions in boot.janet can be implemented more efficiently if the argument type is known to have a fixed length, primarily by creating an array of the correct length, rather than iteratively pushing to an empty array. I think it would be a good idea to expose lengthable? through the corelib.

I don't know that lengthable? is the best name, but it is certainly accurate and unambiguous.

What I'm trying to avoid with all of this is maintaining a user library which re-implements core functions more efficiently. Contributing faster implementations seems like a better idea to me.

sogaiu commented 12 months ago

Exposing doesn't seem bad also from a symmetry perspective with bytes?, indexed?, and dictionary?. Though there doesn't seem to be a callable? (may be there isn't yet a need?).

I tried but failed to think of a better name. If going forward with this, I am in favor of lengthable?. I think it's better than sizable?, has-length?, or i-can-has-length?.

pepe commented 12 months ago

The name is OK, but I am not a native speaker, so :-D.

I would like to see callable? here: https://git.sr.ht/~pepe/gp/tree/master/item/gp/data/navigation.janet#L26 :-).

And 100% for the last sentence of the original post.

sogaiu commented 12 months ago

Regarding callable?, it looks like the definition might end up not being exactly equivalent to the type being :function or :cfunction?

#define JANET_TFLAG_CALLABLE (JANET_TFLAG_FUNCTION | JANET_TFLAG_CFUNCTION | \
        JANET_TFLAG_LENGTHABLE | JANET_TFLAG_ABSTRACT)

Does that work for:

                 callable (or (= :function typ)
                              (= :cfunction typ))]]

?

pepe commented 12 months ago

Oh my bad. Thank you @sogaiu.

pepe commented 12 months ago

But it could be more correct in that place. I will think about it.