From 3148703a224f0f646ca8fff18e7605671f2af839 Mon Sep 17 00:00:00 2001 From: Scott Olsen Date: Mon, 14 Feb 2022 03:31:13 -0500 Subject: [PATCH] feat: add Dynamic.String.to-array (#1382) * feat: add Dynamic.String.to-array Adds a new dynamic function that converts a string to an array of strings, one for each character in the string. In other words, it's the same as Dynamic.String.to-list but the result is an array structure instead of a list. It's also significantly faster than to-list on large inputs. The current implementation of Dynamic.String.to-list takes long to process large inputs, presumably because of its recursive behavior and multiple calls to cons (I'm currently investigating this) (e.g. use read-file then try calling to-list, you may need to wait a while). Contrarily, to-array is nearly instantaneous even when the input string is large. This is because it leverages Haskell's `splitOn` directly, which, when given an empty delimiter, (which is the case for the empty string), splits the entire input sequence. Because "" is the empty list for a string in Haskell's representation, calling split-on with "" results in the splitting behavior. The output also includes the delimiting case, so we drop it using cdr. * test: add test for Dynamic.String.to-array --- core/String.carp | 5 +++++ test/macros.carp | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/core/String.carp b/core/String.carp index e4e02eea..d82917b4 100644 --- a/core/String.carp +++ b/core/String.carp @@ -515,6 +515,11 @@ (if (String.empty? s) '() (cons (String.head s) (String.to-list (String.tail s))))) + + (doc to-array + "Converts a string to an array of strings of each of its characters.") + (defndynamic to-array [s] + (cdr (String.split-on "" s))) ) ) diff --git a/test/macros.carp b/test/macros.carp index e4466ad6..8b09de41 100644 --- a/test/macros.carp +++ b/test/macros.carp @@ -387,6 +387,10 @@ '("h" "e" "l" "l" "o") (String.to-list "hello") "Dynamic.String.to-list works as expected") + (assert-dynamic-equal test + '["h" "e" "l" "l" "o"] + (String.to-array "hello") + "Dynamic.String.to-array works as expected") (assert-equal test 2 (let-do [src 1 dst 0]