Skip to content

Commit 50c7c9d

Browse files
giacomocavalierilpil
authored andcommitted
One final small refactoring
1 parent 79af20f commit 50c7c9d

File tree

1 file changed

+16
-19
lines changed

1 file changed

+16
-19
lines changed

src/gleam/list.gleam

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2317,28 +2317,25 @@ fn max_loop(list, compare, max) {
23172317
pub fn sample(from list: List(a), up_to n: Int) -> List(a) {
23182318
let #(reservoir, rest) = build_reservoir(from: list, sized: n)
23192319

2320-
case rest {
2321-
// If we've already taken all the items there were in the list there's no
2322-
// need to do anything else, we return the entire reservoire.
2323-
[] -> dict.values(reservoir)
2324-
_ ->
2325-
case dict.is_empty(reservoir) {
2326-
// If the reservoire is empty that means we were asking to sample 0 or
2327-
// less items. That doesn't make much sense, so we just return an empty
2328-
// list.
2329-
True -> []
2330-
False -> {
2331-
let w = float.exponential(log_random() /. int.to_float(n))
2332-
dict.values(sample_loop(list, reservoir, n, w))
2333-
}
2334-
}
2320+
case dict.is_empty(reservoir) {
2321+
// If the reservoire is empty that means we were asking to sample 0 or
2322+
// less items. That doesn't make much sense, so we just return an empty
2323+
// list.
2324+
True -> []
2325+
2326+
// Otherwise we keep looping over the remaining part of the list replacing
2327+
// random elements in the reservoir.
2328+
False -> {
2329+
let w = float.exponential(log_random() /. int.to_float(n))
2330+
dict.values(sample_loop(rest, reservoir, n, w))
2331+
}
23352332
}
23362333
}
23372334

23382335
fn sample_loop(
23392336
list: List(a),
23402337
reservoir: Dict(Int, a),
2341-
k: Int,
2338+
n: Int,
23422339
w: Float,
23432340
) -> Dict(Int, a) {
23442341
let skip = {
@@ -2349,9 +2346,9 @@ fn sample_loop(
23492346
case drop(list, skip) {
23502347
[] -> reservoir
23512348
[first, ..rest] -> {
2352-
let reservoir = dict.insert(reservoir, int.random(k), first)
2353-
let w = w *. float.exponential(log_random() /. int.to_float(k))
2354-
sample_loop(rest, reservoir, k, w)
2349+
let reservoir = dict.insert(reservoir, int.random(n), first)
2350+
let w = w *. float.exponential(log_random() /. int.to_float(n))
2351+
sample_loop(rest, reservoir, n, w)
23552352
}
23562353
}
23572354
}

0 commit comments

Comments
 (0)