I realize this avoids actually answering the question, but in your example f(n) is never displayed. It being written in Typst’s math notation is only important to the author. The reason I mention it is because there already exists a tool available to the author for computing such things: code mode.
Taking this idea even further, a system could be created that would collect display and calculation capabilities into one variable:
#let create-pair(short, full, code) = (
short: short(),
full: full,
code: code,
evaluate: (n) => [#short(n: n)$= #code(n)$] //Display inline and the result
)
#let custom-sum = create-pair(
(n: $n$) => $sum_(k=0)^#n k$, //Function to display inline math
$ sum_(k=0)^n k //Plain block math
&= 1 + ... + n \
&= (n(n+1)) / 2 $,
(n) => {(n * (n + 1)) / 2} //Function to calculate the result (code mode)
)
A summation can be expanded as such:
#custom-sum.full
A few examples of summing for various $n$'s:
#(custom-sum.evaluate)(1)
#(custom-sum.evaluate)(5)
#(custom-sum.evaluate)(10)