File tree Expand file tree Collapse file tree 2 files changed +29
-0
lines changed
Expand file tree Collapse file tree 2 files changed +29
-0
lines changed Original file line number Diff line number Diff line change 246246 (set _index (+ 1 _index)) })
247247 _output }))
248248
249+ # @brief Sort elements in a list using a function to compute the key
250+ # @details Use the quicksort algorithm, the original list is not modified.
251+ # @param _L list to sort
252+ # @param _key function called on each element of the list, returning a unique key to use for sorting
253+ # =begin
254+ # (let ranges [[3 5] [10 14] [16 20] [12 18]])
255+ # (let sorted (sortByKey ranges (fun (e) (head e))))
256+ # (print sorted) # [[3 5] [10 14] [12 18] [16 20]]
257+ # =end
258+ # @author https://github.com/SuperFola
259+ (let sortByKey (fun (_L _key) {
260+ (if (empty? _L)
261+ []
262+ {
263+ (let _pivot_val (head _L))
264+ (let _pivot (_key _pivot_val))
265+
266+ (mut _less (sortByKey (filter (tail _L) (fun (e) (< (_key e) _pivot))) _key))
267+ (let _more (sortByKey (filter (tail _L) (fun (e) (>= (_key e) _pivot))) _key))
268+
269+ (concat! _less [_pivot_val] _more)
270+ _less }) }))
271+
249272# @brief Apply a given function to each element of a list
250273# @param _L the list to work on
251274# @param _f the function to apply to each element
Original file line number Diff line number Diff line change 55(let a [1 2 3])
66(let b [4 5 6])
77(let zipped [[1 5] [2 6] [3 7] [4 8]])
8+ (let reversedZipped [[4 8] [3 7] [2 6] [1 5]])
89
910(test:suite list {
1011 (test:case "builtins" {
7879 (test:eq (list:filter a (fun (e) (> e 100))) [])
7980 (test:eq (list:filter [] (fun (e) (> e 100))) []) })
8081
82+ (test:case "sortByKey" {
83+ (test:eq (list:sortByKey reversedZipped (fun (e) (head e))) zipped)
84+ (test:eq (list:sortByKey [9 8 1] (fun (e) e)) [1 8 9])
85+ (test:eq (list:sortByKey [] (fun (e) e)) []) })
86+
8187 (test:case "map" {
8288 (test:eq (list:map b (fun (e) (* e e))) [16 25 36])
8389 (test:eq (list:map [] (fun (e) (* e e))) []) })
You can’t perform that action at this time.
0 commit comments