Skip to content

Commit 84b04cd

Browse files
committed
feat(random): adding a new package 'Random', with random:choice
1 parent 8fed003 commit 84b04cd

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

Random.ark

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# @brief Select a random element from a list
2+
# @details If the list is empty, returns nil
3+
# @param _L list of elements
4+
# =begin
5+
# (import std.Random)
6+
# (print (random:choice [1 2 3]))
7+
# =end
8+
# @author https://github.com/SuperFola
9+
(let choice (fun (_L)
10+
(if (empty? _L)
11+
nil
12+
(if (= 1 (len _L))
13+
(head _L)
14+
(@ _L (random 0 (- (len _L) 1)))))))
15+

tests/all.ark

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
(import list-tests)
99
(import macros-tests)
1010
(import math-tests)
11+
(import random-tests)
1112
(import range-tests)
1213
(import string-tests)
1314
(import switch-tests)
@@ -26,6 +27,7 @@
2627
list-tests:list-output
2728
macros-tests:macros-output
2829
math-tests:math-output
30+
random-tests:random-output
2931
range-tests:range-output
3032
string-tests:string-output
3133
switch-tests:switch-output

tests/random-tests.ark

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
(import std.Random)
2+
(import std.Testing)
3+
4+
(test:suite random {
5+
(test:case "choice" {
6+
(test:eq nil (random:choice []))
7+
(test:eq nil (random:choice ""))
8+
(test:eq 1 (random:choice [1]))
9+
(test:eq "1" (random:choice "1"))
10+
11+
# have to repeat the test to be sure that we hit every index
12+
(test:eq 1 (random:choice [1 1 1]))
13+
(test:eq 1 (random:choice [1 1 1]))
14+
(test:eq 1 (random:choice [1 1 1]))
15+
(test:eq 1 (random:choice [1 1 1]))
16+
(test:eq 1 (random:choice [1 1 1]))
17+
(test:eq "1" (random:choice "111"))
18+
(test:eq "1" (random:choice "111"))
19+
(test:eq "1" (random:choice "111"))
20+
(test:eq "1" (random:choice "111"))
21+
(test:eq "1" (random:choice "111")) })})
22+

0 commit comments

Comments
 (0)