Added sort function

This commit is contained in:
Benjamin Vedder 2022-03-07 17:31:17 +01:00
parent 88d8e3385e
commit 0e8ccaf070
2 changed files with 46 additions and 0 deletions

View File

@ -956,6 +956,26 @@ Filter list by keeping the elements on which f returns true. Example:
> (3 2 4)
```
#### sort
```clj
(sort f lst)
```
Sort list lst using comparison function f. Example:
```clj
(sort < '(5 6 2 1 5 63 33 7 7 8))
> (1 2 5 5 6 7 7 8 33 63)
(sort > '(5 6 2 1 5 63 33 7 7 8))
> (63 33 8 7 7 6 5 5 2 1)
; Split sentence to words and sort them in ascending order
(sort str-cmp-asc (str-split "this is a string" " "))
> ("a" "is" "string" "this")
```
### String Manipulation
#### str-from-n
@ -1137,6 +1157,22 @@ Compare strings str1 and str2. Works in the same way as the strcmp-function in C
> 15
```
#### str-cmp-asc
```clj
(str-cmp-asc str1 str1)
```
Return true if str1 comes before str2, nil otherwise. Useful for sorting strings using the [sort](#sort) function in ascending order.
#### str-cmp-dsc
```clj
(str-cmp-dsc str1 str1)
```
Return true if str2 comes before str1, nil otherwise. Useful for sorting strings using the [sort](#sort) function in descending order.
#### str-len
```clj

View File

@ -85,6 +85,16 @@ static const char* functions[] = {
"))",
"(defun str-len (str) (- (buflen str) 1))",
"(defun sort (f lst)"
"(let ((insert (lambda (elt f sorted-lst)"
"(if (= sorted-lst nil) (list elt)"
"(if (f elt (car sorted-lst)) (cons elt sorted-lst)"
"(cons (car sorted-lst) (insert elt f (cdr sorted-lst))))))))"
"(if (= lst nil) nil (insert (car lst) f (sort f (cdr lst))))))",
"(defun str-cmp-asc (a b) (< (str-cmp a b) 0))",
"(defun str-cmp-dsc (a b) (> (str-cmp a b) 0))",
};
static const char* macros[] = {