Skip to content

Commit 6d4ff27

Browse files
authored
📦 Add chunks and string to stdlib (#72)
1 parent 2bc1431 commit 6d4ff27

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

‎ndc_lib/src/stdlib/sequence.rs‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,7 @@ mod inner {
486486
)
487487
}
488488

489-
//// Returns al prefixes of a sequence, each as a list.
489+
/// Returns al prefixes of a sequence, each as a list.
490490
pub fn prefixes(seq: &mut Sequence) -> Value {
491491
// Special case for string which is more efficient and doesn't produce lists of characters
492492
if let Sequence::String(string) = &seq {
@@ -676,6 +676,23 @@ mod inner {
676676

677677
Ok(Value::list(out))
678678
}
679+
680+
/// Split the input sequence into evenly sized chunks. If the input length of the sequence
681+
/// is not dividable by the chunk_size the last chunk will contain fewer elements.
682+
pub fn chunks(seq: &mut Sequence, chunk_size: usize) -> anyhow::Result<Value> {
683+
if chunk_size == 0 {
684+
return Err(anyhow!("chunk size must be non-zero"));
685+
}
686+
687+
let iter = mut_seq_to_iterator(seq);
688+
689+
Ok(Value::list(
690+
iter.chunks(chunk_size)
691+
.into_iter()
692+
.map(|chunk| Value::list(chunk.collect_vec()))
693+
.collect_vec(),
694+
))
695+
}
679696
}
680697

681698
fn fold_iterator(

‎ndc_lib/src/stdlib/string.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ mod inner {
3131
format!("{left}{right}")
3232
}
3333

34+
/// Returns the provided value as a string
35+
pub fn string(value: &Value) -> String {
36+
format!("{value}")
37+
}
38+
3439
/// Returns the Unicode code point of a 1-length string.
3540
pub fn ord(string: &str) -> anyhow::Result<i64> {
3641
if string.chars().count() == 1 {

0 commit comments

Comments
 (0)