Last active
August 19, 2022 19:19
-
-
Save GiuseppeChillemi/8574182a514e0c32f1ab2ece0f60a497 to your computer and use it in GitHub Desktop.
Sort a series by the length of its elements, from smaller to bigger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;Red [] | |
Rebol [] | |
sort-by-length: func [ | |
[catch] | |
"Sort a block by the length of its components from smaller to bigger" | |
data [block!] "Block of elements" | |
/safe "Elements type can be mixed" | |
/reverse "Reverse the order of sorting" | |
/local | |
out-data | |
elements-type | |
myname | |
] [ | |
myname: "Sort-by-Length" | |
out-data: copy [] | |
forall data [ | |
either series? :data/1 [ | |
either empty? out-data [ | |
elements-type: type? :data/1 | |
insert/only out-data :data/1 | |
] [ | |
if all [safe <> true elements-type <> (type? :data/1)] [ | |
print rejoin [ | |
"Function: " myname lf | |
tab "Element at index: " index? data " is: " mold type? :data/1 lf | |
tab "expected: " mold elements-type lf | |
] | |
throw make error! "Data type non homogeneous" | |
] | |
forall out-data [ | |
case [ | |
all [reverse (length? :out-data/1) < (length? :data/1)] [ | |
insert/only out-data :data/1 | |
break | |
] | |
all [reverse <> true (length? :out-data/1) > (length? :data/1)] [ | |
insert/only out-data :data/1 | |
break | |
] | |
] | |
if (length? out-data) = 1 [ | |
insert/only next out-data :data/1 | |
break | |
] | |
] | |
] | |
out-data: head out-data | |
] [ | |
print rejoin [ | |
"Function: " myname lf | |
tab "Element at index: " index? data " is: " mold type? :data/1 lf | |
tab "should be a SERIES!" lf | |
] | |
throw make error! "Datatype not a series!" | |
] | |
] | |
head out-data | |
] | |
;tests | |
[ | |
inn-data: ["aaa" "aaaaaaa" "aaaaaaaaaaa" "a"] | |
probe sorted-series: sort-by-length inn-data | |
;["a" "aaa" "aaaaaaa" "aaaaaaaaaaa"] | |
inn-data: ["aaa" "aaaaaaa" "aaaaaaaaaaa" "a"] | |
probe sorted-series: sort-by-length/reverse inn-data | |
;["aaaaaaaaaaa" "aaaaaaa" "aaa" "a"] | |
inn-data: ["aaa" "aaaaaaa" "aaaaaaaaaaa" "a"] | |
append/only inn-data [1] | |
probe sorted-series: sort-by-length/safe inn-data | |
;["a" [1] "aaa" "aaaaaaa" "aaaaaaaaaaa"] | |
inn-data: ["aaa" "aaaaaaa" "aaaaaaaaaaa" "a"] | |
append/only inn-data [1] | |
probe sorted-series: sort-by-length inn-data | |
;Function: Sort-by-Length | |
; Element at index: 5 is: block! | |
; expected: string! | |
inn-data: ["aaa" "aaaaaaa" "aaaaaaaaaaa" "a"] | |
append/only inn-data 1 | |
probe sorted-series: sort-by-length inn-data | |
;Function: Sort-by-Length | |
; Element at index: 5 is: integer! | |
; should be a SERIES! | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment