1
0
mirror of https://github.com/janet-lang/janet synced 2024-06-24 06:03:17 +00:00

add lengthable?

This commit is contained in:
primo-ppcg 2023-08-10 20:54:13 +07:00
parent 7049f658ec
commit 795b64d4d1
2 changed files with 35 additions and 18 deletions

View File

@ -1554,32 +1554,41 @@
(defn keys (defn keys
"Get the keys of an associative data structure." "Get the keys of an associative data structure."
[x] [x]
(def arr (array/new-filled (length x))) (if (lengthable? x)
(var i 0) (do
(eachk k x (def arr (array/new-filled (length x)))
(put arr i k) (var i 0)
(++ i)) (eachk k x
arr) (put arr i k)
(++ i))
arr)
(seq [k :keys x] k)))
(defn values (defn values
"Get the values of an associative data structure." "Get the values of an associative data structure."
[x] [x]
(def arr (array/new-filled (length x))) (if (lengthable? x)
(var i 0) (do
(each v x (def arr (array/new-filled (length x)))
(put arr i v) (var i 0)
(++ i)) (each v x
arr) (put arr i v)
(++ i))
arr)
(seq [v :in x] v)))
(defn pairs (defn pairs
"Get the key-value pairs of an associative data structure." "Get the key-value pairs of an associative data structure."
[x] [x]
(def arr (array/new-filled (length x))) (if (lengthable? x)
(var i 0) (do
(eachp p x (def arr (array/new-filled (length x)))
(put arr i p) (var i 0)
(++ i)) (eachp p x
arr) (put arr i p)
(++ i))
arr)
(seq [p :pairs x] p)))
(defn frequencies (defn frequencies
"Get the number of occurrences of each value in an indexed data structure." "Get the number of occurrences of each value in an indexed data structure."

View File

@ -680,6 +680,13 @@ JANET_CORE_FN(janet_core_is_dictionary,
return janet_wrap_boolean(janet_checktypes(argv[0], JANET_TFLAG_DICTIONARY)); return janet_wrap_boolean(janet_checktypes(argv[0], JANET_TFLAG_DICTIONARY));
} }
JANET_CORE_FN(janet_core_is_lengthable,
"(lengthable? x)",
"Check if x is a bytes, indexed, or dictionary.") {
janet_fixarity(argc, 1);
return janet_wrap_boolean(janet_checktypes(argv[0], JANET_TFLAG_LENGTHABLE));
}
JANET_CORE_FN(janet_core_signal, JANET_CORE_FN(janet_core_signal,
"(signal what x)", "(signal what x)",
"Raise a signal with payload x. ") { "Raise a signal with payload x. ") {
@ -1077,6 +1084,7 @@ static void janet_load_libs(JanetTable *env) {
JANET_CORE_REG("bytes?", janet_core_is_bytes), JANET_CORE_REG("bytes?", janet_core_is_bytes),
JANET_CORE_REG("indexed?", janet_core_is_indexed), JANET_CORE_REG("indexed?", janet_core_is_indexed),
JANET_CORE_REG("dictionary?", janet_core_is_dictionary), JANET_CORE_REG("dictionary?", janet_core_is_dictionary),
JANET_CORE_REG("lengthable?", janet_core_is_lengthable),
JANET_CORE_REG("slice", janet_core_slice), JANET_CORE_REG("slice", janet_core_slice),
JANET_CORE_REG("range", janet_core_range), JANET_CORE_REG("range", janet_core_range),
JANET_CORE_REG("signal", janet_core_signal), JANET_CORE_REG("signal", janet_core_signal),