janet-lang / janet

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

Add `lengthable?` #1247

Closed primo-ppcg closed 1 year ago

primo-ppcg commented 1 year ago

Check if x is a bytes, indexed, or dictionary.


- Allows potentially non-lengthable items for `keys`, `values`, and `pairs`, as used for example in [spork/generators](https://github.com/janet-lang/spork/blob/ce3e4377b61f14cf4221bcb3c0c10a96382aede8/spork/generators.janet#L18-L21).

There's a few other core functions that I think could benefit from knowing whether an iterable has a pre-determined length.
sogaiu commented 1 year ago

I tried out the changes a bit.

The spork test bit mentioned here seems to be resolved. Ran the spork test suite and that was fine too.

Also ran the tests I've been running across some other repositories with no issues :+1:

primo-ppcg commented 1 year ago

Actually, these functions don't make much sense on a fiber.

For example:

(defn gen []
  (coro
    (for i 0 10 (yield i))))

(keys (gen))
# ->
@[0 0 0 0 0 0 0 0 0 0]

This is true of every major Janet release; the next key of an active fiber is always 0. I believe it is more correct for keys to produce an error, than to return an array of zeros.

Instead, I think generators/to-array should be rewritten to do as it says: consume the values into an array. https://github.com/janet-lang/spork/pull/148