Skip to content

Commit

Permalink
refactor: luau qsv_accumulate initial value
Browse files Browse the repository at this point in the history
Per #2536 (comment)

> If init is not specified then y[1] should be set to x[1] where y is the output vector and x is the input vector, not 0

cc @ggrothendieck
  • Loading branch information
jqnatividad committed Feb 18, 2025
1 parent 7cdf9db commit cda17f4
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/cmd/luau.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2502,7 +2502,8 @@ fn setup_helpers(
_ => 0.0,
}
} else {
0.0 // Always start with 0.0 as default initial value
// Always start with the current value as the initial value
curr_value
};
luau.globals().set(&*state_name, init_value)?;
init_value
Expand Down
45 changes: 45 additions & 0 deletions tests/test_luau.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3103,6 +3103,51 @@ return qsv_accumulate("value", weighted_sum, 0)
assert_eq!(got, expected);
}

#[test]
fn luau_accumulate_custom_sum_function_no_initial_value() {
let wrk = Workdir::new("luau_accumulate_custom_sum_function_no_initial_value");
wrk.create(
"data.csv",
vec![
svec!["value"],
svec!["10"],
svec!["20"],
svec!["30"],
svec!["40"],
svec!["50"],
],
);

let mut cmd = wrk.command("luau");
cmd.arg("map")
.arg("accumulated")
.arg(
r#"
-- This is the MAIN LOOP
-- Define a custom accumulator function that keeps a weighted sum
-- where each new value is weighted by its position
-- we define the function inside the MAIN LOOP to access the _IDX variable
function weighted_sum(acc, x)
return acc + x * _IDX
end
return qsv_accumulate("value", weighted_sum)
"#,
)
.arg("data.csv");

let got: Vec<Vec<String>> = wrk.read_stdout(&mut cmd);
let expected = vec![
svec!["value", "accumulated"],
svec!["10", "20"], // 10 + 10 * 1
svec!["20", "60"], // 20 + 20 * 2
svec!["30", "150"], // 60 + 30 * 3
svec!["40", "310"], // 150 + 40 * 4
svec!["50", "560"], // 310 + 50 * 5
];
assert_eq!(got, expected);
}

#[test]
fn luau_accumulate_custom_sum_function_with_initial_value() {
let wrk = Workdir::new("luau_accumulate_custom_sum_function_with_initial_value");
Expand Down

0 comments on commit cda17f4

Please sign in to comment.