Skip to content

Commit d4286b3

Browse files
committed
feat(list): adding list:median
1 parent 36ee48c commit d4286b3

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

List.ark

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,24 @@
201201
(set _index (+ 1 _index)) })
202202
_output }))
203203

204-
(import std.Math :min :max)
204+
(import std.Math :min :max :even)
205+
206+
# @brief Find the median in a list of numbers
207+
# @param _L list of numbers
208+
# @details The original list is not modified.
209+
# =begin
210+
# (let value (list:median [0 1 2 3 5 8])) # 2.5
211+
# =end
212+
# @author https://github.com/SuperFola
213+
(let median (fun ((ref _L)) {
214+
(let _n (len _L))
215+
(if (= 0 _n)
216+
nil
217+
{
218+
(let _s (sort _L))
219+
(if (math:even _n)
220+
(/ (+ (@ _s (- (/ _n 2) 1)) (@ _s (/ _n 2))) 2)
221+
(@ _s (/ _n 2))) }) }))
205222

206223
# @brief Drop the first n elements of a list
207224
# @param _L the list to work on

tests/list-tests.ark

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,14 @@
6464
(test:eq (list:max b) 6)
6565
(test:eq (list:max [-1]) -1) })
6666

67+
(test:case "median" {
68+
(test:eq (list:median []) nil)
69+
(test:eq (list:median [1]) 1)
70+
(test:eq (list:median [1 2]) 1.5)
71+
(test:eq (list:median [2 1 3]) 2)
72+
(test:eq (list:median [1 2 2 1]) 1.5)
73+
(test:eq (list:median [1 2 2 1 3]) 2) })
74+
6775
(test:case "drop" {
6876
(test:eq (list:drop a 0) [1 2 3])
6977
(test:eq (list:drop a 1) [2 3])

0 commit comments

Comments
 (0)