lib-tan-core 0.16.0

The core library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
use tan::{
    context::Context,
    error::Error,
    eval::{invoke, invoke_func},
    expr::{expr_clone, format_value, Expr},
    util::{
        args::{unpack_arg, unpack_array_arg, unpack_array_mut_arg, unpack_int_arg},
        module_util::require_module,
    },
};

use super::cmp::rust_ordering_from_tan_ordering;

// #insight Iterable is more general than Sequence. For example you could consider
// a Map as an Iterable it's more of a stretch to think of it as a Sequence.

// #todo Rename to `iter.rs`.

// #todo Find a better name
pub fn list_cons(args: &[Expr]) -> Result<Expr, Error> {
    let [head, tail] = args else {
        return Err(Error::invalid_arguments(
            "requires `head` and `tail` arguments",
            None,
        ));
    };

    let Some(tail) = tail.as_list() else {
        return Err(Error::invalid_arguments(
            "`tail` argument should be a List",
            tail.range(),
        ));
    };

    // #todo this is slow!
    let mut cons_items = vec![expr_clone(head.unpack())];
    for expr in tail {
        cons_items.push(expr_clone(expr));
    }

    Ok(Expr::List(cons_items))
}

// #todo find better name, match Array and String.
pub fn list_count(args: &[Expr]) -> Result<Expr, Error> {
    let [list, ..] = args else {
        return Err(Error::invalid_arguments("requires `list` argument", None));
    };

    let Some(list) = list.as_list() else {
        return Err(Error::invalid_arguments(
            "`list` argument should be a List",
            list.range(),
        ));
    };

    Ok(Expr::Int(list.len() as i64))
}

// #todo implement slice _and_ takes

// #todo implement sort! and sort (or sort, to-sorted)
// #todo add put/insert at index

// #todo implement generically for all iterables/countables, etc.

pub fn array_eq(args: &[Expr]) -> Result<Expr, Error> {
    // Use macros to monomorphise functions? or can we leverage Rust's generics? per viariant? maybe with cost generics?
    // #todo support overloading,
    // #todo support multiple arguments.

    let a = unpack_array_arg(args, 0, "a")?;
    let b = unpack_array_arg(args, 1, "b")?;

    Ok(Expr::Bool(*a == *b))
}

// #todo version that returns a new sequence
// #todo also consider insert, insert-back, append names
// #todo item or element?
pub fn array_push(args: &[Expr]) -> Result<Expr, Error> {
    let [array, element] = args else {
        return Err(Error::invalid_arguments(
            "requires `this` and `element` argument",
            None,
        ));
    };

    let Some(mut elements) = array.as_array_mut() else {
        return Err(Error::invalid_arguments(
            "`array` argument should be a Array",
            array.range(),
        ));
    };

    elements.push(element.unpack().clone()); // #todo hmm this clone!

    // #todo what to return?
    Ok(Expr::None)
}

// #todo Add unit-test.
// (put arr index value)
pub fn array_put(args: &[Expr]) -> Result<Expr, Error> {
    let mut array = unpack_array_mut_arg(args, 0, "array")?;
    let index = unpack_int_arg(args, 1, "index")?;
    let element = unpack_arg(args, 2, "element")?;

    // #todo Remove this clone.
    array[index as usize] = element.clone();

    // #todo What should we return?
    Ok(Expr::None)
}

// #todo generic Seq/extend, append on arrays, prepends on linked-lists.
// #todo support concatenation of more than two arrays.
// #todo find a good name
// #todo consider the `++` operator
pub fn array_concat_mut(args: &[Expr]) -> Result<Expr, Error> {
    let [array1, array2] = args else {
        return Err(Error::invalid_arguments("requires two arguments", None));
    };

    let Some(mut array1) = array1.as_array_mut() else {
        return Err(Error::invalid_arguments(
            "`array1` argument should be a Array",
            array1.range(),
        ));
    };

    let Some(mut array2) = array2.as_array_mut() else {
        return Err(Error::invalid_arguments(
            "`array2` argument should be a Array",
            array2.range(),
        ));
    };

    array1.append(&mut array2);

    // #todo what to return?
    Ok(Expr::None)
}

pub fn array_concat(args: &[Expr]) -> Result<Expr, Error> {
    let a = unpack_array_arg(args, 0, "a")?;
    let b = unpack_array_arg(args, 1, "b")?;

    // #todo Check if a or b is empty and optimize!

    let c: Vec<Expr> = a.iter().chain(b.iter()).cloned().collect();

    Ok(Expr::array(c))
}

// #todo consider the name intercalate from haskell?
// #todo can we find a more specific name?
// #todo hm, it joins as strings, not very general, should move to string?
/// (join names "\n")
pub fn array_join(args: &[Expr]) -> Result<Expr, Error> {
    let Some(array) = args.first() else {
        return Err(Error::invalid_arguments("requires `array` argument", None));
    };

    let separator = args.get(1);
    let separator = if separator.is_some() {
        let Some(str) = separator.unwrap().as_stringable() else {
            return Err(Error::invalid_arguments(
                "the `separator` should be a Stringable",
                None,
            ));
        };
        str
    } else {
        ""
    };

    let Some(array) = array.as_array() else {
        return Err(Error::invalid_arguments(
            "`array` argument should be a Array",
            array.range(),
        ));
    };

    let elements: Vec<String> = array.iter().map(format_value).collect();

    Ok(Expr::String(elements.join(separator)))
}

// #todo do we really want to support the no-argument case?
/// (skip items 5) ; skips the first 5 elements
/// (skip items) ; skips the first element
pub fn array_skip(args: &[Expr]) -> Result<Expr, Error> {
    // #insight
    // An alternative name could be `drop` but for the moment we reserve this for
    // the memory operation. Additionally, skip is a bit more descriptive.
    let Some(array) = args.first() else {
        return Err(Error::invalid_arguments("requires `array` argument", None));
    };

    let n = args.get(1);
    let n = if n.is_some() {
        let Some(n) = n.unwrap().as_int() else {
            return Err(Error::invalid_arguments("`n` should be an Int", None));
        };
        n
    } else {
        1
    };

    let Some(array) = array.as_array() else {
        return Err(Error::invalid_arguments(
            "`array` argument should be a Array",
            array.range(),
        ));
    };

    let elements: Vec<Expr> = array.iter().skip(n as usize).cloned().collect();

    Ok(Expr::array(elements))
}

// #insight use the word Iterable instead of Sequence/Seq, more generic (can handle non-sequences, e.g. maps)
// #insight could also use Countable

// #todo match the corresponding function in String.
// #todo rename to `get-length`?
// #todo implement generically for iterables.
pub fn array_count(args: &[Expr]) -> Result<Expr, Error> {
    let [array, ..] = args else {
        return Err(Error::invalid_arguments("requires `array` argument", None));
    };

    let Some(array) = array.as_array() else {
        return Err(Error::invalid_arguments(
            "`array` argument should be a Array",
            array.range(),
        ));
    };

    Ok(Expr::Int(array.len() as i64))
}

// #todo implement with tan code!
pub fn array_is_empty(args: &[Expr]) -> Result<Expr, Error> {
    let [array, ..] = args else {
        return Err(Error::invalid_arguments("requires `array` argument", None));
    };

    let Some(array) = array.as_array() else {
        return Err(Error::invalid_arguments(
            "`array` argument should be a Array",
            array.range(),
        ));
    };

    Ok(Expr::Bool(array.len() == 0))
}

pub fn array_contains(args: &[Expr]) -> Result<Expr, Error> {
    let [array, element] = args else {
        return Err(Error::invalid_arguments(
            "requires `this` and `element` argument",
            None,
        ));
    };

    let Some(elements) = array.as_array_mut() else {
        return Err(Error::invalid_arguments(
            "`array` argument should be a Array",
            array.range(),
        ));
    };

    Ok(Expr::Bool(elements.contains(element.unpack())))
}

// #todo add unit tests.
pub fn array_map(args: &[Expr], context: &mut Context) -> Result<Expr, Error> {
    let [seq, func] = args else {
        return Err(Error::invalid_arguments(
            "requires `array` and `func` arguments",
            None,
        ));
    };

    // #todo should relax to allow for Iterable.
    let Some(input_values) = seq.as_array() else {
        return Err(Error::invalid_arguments(
            "`seq` must be an `Array`",
            seq.range(),
        ));
    };

    // #insight cannot use map, because of the `?` operator.

    let mut output_values: Vec<Expr> = Vec::new();

    // #todo make sure that errors in the mapping function are propagated.

    for x in input_values.iter() {
        // #todo can we remove this clone somehow?
        let args = vec![expr_clone(x)];
        // let args = vec![eval(x, context)?];
        // #todo #hack need to rething invoke_func/invoke_func_inner!!
        output_values.push(invoke(func, args, context)?);
    }

    Ok(Expr::array(output_values))
}

// #todo this can actually be implemented with invoke_func.
// #todo how to implement this? -> implement with tan code!
pub fn array_filter(_args: &[Expr]) -> Result<Expr, Error> {
    todo!();

    // // #todo
    // let [seq, predicate_fn] = args else {
    //     return Err(Error::invalid_arguments(
    //         "requires `this` and `predicate-fn` arguments",
    //         None,
    //     ));
    // };

    // let Some(arr) = seq.as_array() else {
    //     return Err(Error::invalid_arguments(
    //         "`filter` requires a `Seq` as the first argument",
    //         seq.range(),
    //     ));
    // };

    // let prev_scope = context.scope.clone();
    // // context.scope = Rc::new(Scope::new(prev_scope.clone()));

    // let mut results: Vec<Expr> = Vec::new();

    // for x in arr.iter() {
    //     // #todo how to call a closure?

    //     // // #todo array should have Ann<Expr> use Ann<Expr> everywhere, avoid the clones!
    //     // context.scope.insert(sym, x.clone());
    //     // let result = eval(body, context)?;
    //     // // #todo replace the clone with custom expr::ref/copy?
    //     // results.push(result.unpack().clone());
    // }

    // // context.scope = prev_scope.clone();

    // // #todo intentionally don't return a value, reconsider this?
    // Ok(Expr::array(results).into())
}

// #todo implement first, last

#[inline]
fn sort_array_items(array_items: &mut [Expr], func: &Expr, context: &mut Context) {
    // #todo validate func is a comparator.
    // #todo validate that params has the correct structure.

    // #todo #IMPORTANT, only sorts Int arrays!
    // #hint Use e.g. (sort a (Func [a b] (Int (- a b))))

    array_items.sort_by(|x, y| {
        // #todo how to handle errors here?
        // #todo should we evaluate array items?
        // #insight args are already evaluated!
        // let args = vec![eval(x, context).unwrap(), eval(y, context).unwrap()];
        let args = vec![x.clone(), y.clone()];
        let tan_ordering = invoke_func(func, args, context).unwrap();
        rust_ordering_from_tan_ordering(&tan_ordering).unwrap()
    });
}

pub fn array_sort(args: &[Expr], context: &mut Context) -> Result<Expr, Error> {
    // #todo Find a good name for the array argument.
    let xs = unpack_array_arg(args, 0, "xs")?;
    let func = unpack_arg(args, 1, "func")?;

    let mut xs_sorted = xs.clone();

    sort_array_items(&mut xs_sorted, func, context);

    Ok(Expr::array(xs_sorted))
}

// #todo Use (sort #mut arr (Func [a b] (- a b)))
// #todo implement sort!, sort, sort-by!, sort-by
// #todo need to introduce Comparable trait and (cmp ...) or (compare ...)
// #todo need to introduce Ordering trait
// (sort! [9 2 7] (Func [a b] (- a b)))
// (sort! [9 2 7] (-> [a b] (- a b)))
pub fn array_sort_mut(args: &[Expr], context: &mut Context) -> Result<Expr, Error> {
    let [array, func] = args else {
        return Err(Error::invalid_arguments(
            "requires `array` and `func` arguments",
            None,
        ));
    };

    let Some(mut array_items) = array.as_array_mut() else {
        return Err(Error::invalid_arguments(
            "`array` argument should be a Array",
            array.range(),
        ));
    };

    sort_array_items(&mut array_items, func, context);

    // #todo Don't return the array, skip the clone!!

    // #insight interesting that we are also returning the input.

    // Ok(Expr::array(array_items.clone()))
    Ok(array.clone())
}

// #todo enforce range within string length
// #todo rename to `cut`? (as in 'cut a slice')
// #todo relation with range?
// #todo pass range as argument?
// #todo support negative index: -1 => length - 1
// #insight negative index _may_ be problematic if the index is computed and returns negative by mistake.
/// (slice arr 2 5)
/// (slice arr 2)
/// (slice arr 2 -2) ; -2 is length - 2
pub fn array_slice(args: &[Expr]) -> Result<Expr, Error> {
    let [this, start, ..] = args else {
        return Err(Error::invalid_arguments(
            "requires `this` and start arguments",
            None,
        ));
    };

    let Some(elements) = this.as_array() else {
        return Err(Error::invalid_arguments(
            "`this` argument should be an Array",
            this.range(),
        ));
    };

    let Some(start) = start.as_int() else {
        return Err(Error::invalid_arguments(
            "`start` argument should be an Int",
            this.range(),
        ));
    };

    let end = if let Some(end) = args.get(2) {
        let Some(end) = end.as_int() else {
            return Err(Error::invalid_arguments(
                "`end` argument should be an Int",
                this.range(),
            ));
        };
        end
    } else {
        elements.len() as i64
    };

    let start = start as usize;
    let end = if end < 0 {
        // #todo supporting negative index may hide errors if the index is computed
        // #todo offer a link to only support negative values for constant index
        // If the end argument is negative it indexes from the end of the string.
        (elements.len() as i64 + end) as usize
    } else {
        end as usize
    };

    let slice = &elements[start..end];

    Ok(Expr::array(slice))
}

// #todo Consider different names: roll, rolled, rolling
// #todo Consider eager (roll) and lazy (rolling/rolled) versions.
// #todo Is this generic?
pub fn array_roll(args: &[Expr]) -> Result<Expr, Error> {
    let window_size = unpack_int_arg(args, 0, "window-size")?;
    let items = unpack_array_arg(args, 1, "items")?;

    let windows = items.windows(window_size as usize);

    let mut rolled_items = Vec::new();
    for window in windows {
        rolled_items.push(Expr::array(window));
    }

    Ok(Expr::array(rolled_items))
}

pub fn setup_lib_seq(context: &mut Context) {
    // #todo should put in `seq` module and then into `prelude`.
    let module = require_module("prelude", context);

    module.insert_invocable("=$$Array$$Array", Expr::foreign_func(&array_eq));

    // #todo introduce `++` overload?
    module.insert_invocable("cons", Expr::foreign_func(&list_cons));
    module.insert_invocable("count", Expr::foreign_func(&list_count));
    module.insert_invocable("count$$List", Expr::foreign_func(&list_count));

    // #todo add type qualifiers!
    module.insert_invocable("push", Expr::foreign_func(&array_push));
    // #todo Add more signatures, or make generic somehow.
    module.insert_invocable("put$$Array$$Int$$Int", Expr::foreign_func(&array_put));
    module.insert_invocable("put$$Array$$Int$$Float", Expr::foreign_func(&array_put));
    // #todo Reconsider the `!` suffix, reconsider the name.
    // #todo Consider concat-mut
    // #todo also introduce `++`, `++=`, versions
    module.insert_invocable("concat!", Expr::foreign_func(&array_concat_mut));

    module.insert_invocable("concat", Expr::foreign_func(&array_concat));
    module.insert_invocable("++", Expr::foreign_func(&array_concat));

    // (map (Func [x] (+ x 1)) [1 2 3]) ; => [2 3 4]
    // (map (Fn x (+ x 1)) [1 2 3]) ; => [2 3 4]
    // (map (-> x (+ x 1)) [1 2 3]) ; => [2 3 4]
    // (map \(+ % 1) [1 2 3])
    module.insert_invocable("map", Expr::foreign_func_mut_context(&array_map));

    module.insert_invocable("join", Expr::foreign_func(&array_join));
    module.insert_invocable("skip", Expr::foreign_func(&array_skip));
    // #todo rename to (get-length) or something, match with String and other collection types.
    module.insert_invocable("count", Expr::foreign_func(&array_count));
    module.insert_invocable("count$$Array", Expr::foreign_func(&array_count));
    // #todo make contains? generic!
    module.insert_invocable("contains?", Expr::foreign_func(&array_contains));
    module.insert_invocable("contains?$$Array$$Int", Expr::foreign_func(&array_contains));
    module.insert_invocable(
        "contains?$$Array$$String",
        Expr::foreign_func(&array_contains),
    );
    module.insert_invocable("is-empty?", Expr::foreign_func(&array_is_empty));
    module.insert_invocable("sort", Expr::foreign_func_mut_context(&array_sort));
    module.insert_invocable("sort!", Expr::foreign_func_mut_context(&array_sort_mut));

    // #todo slice is to general works both as noun and verb, try to find an explicit verb? e.g. `cut` or `carve`
    // #todo alternatively use something like `get-slice` or `cut-slice` or `carve-slice`.
    // module.insert_invocable("slice", Expr::foreign_func(&array_slice)));
    module.insert_invocable("slice$$Array$$Int", Expr::foreign_func(&array_slice));
    module.insert_invocable("slice$$Array$$Int$$Int", Expr::foreign_func(&array_slice));

    module.insert_invocable("roll", Expr::foreign_func(&array_roll));

    // let module = require_module("seq", context);

    // println!("--- YO!");
    // // #insight eval additional code implemented in Tan.
    // if let Err(errors) = eval_module("seq", context, true) {
    //     // #todo improve formatting here.
    //     eprintln!("{errors:?}");
    // }
}

// #todo introduce FuncMut?
// #todo maybe (map ...) should emit warning for FuncMut/ForeignFuncMut