let operator for mathjs? #3355
gwhitney
started this conversation in
Design decisions
Replies: 1 comment
-
The source of the "array trick" for let-like behavior was #3128, it turns out. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Sometimes it is useful to define a sub-expression and then use the result of that, perhaps multiple times, in another expression. For example, you might calculate the index of the largest triangular number less than
n
viafloor((sqrt(1+8*n)-1)/2)
and then want to call thatt
and compute how much largern
is than that triangular number withn - (t+1)t/2
.A while back someone posted on one of the issues or discussions here a trick to do just this (but sadly I can't find the exact reference at the moment). It was to write
[t = floor((sqrt(1+8*n)-1)/2), n - (t+1)t/2][2]
It works, but this syntax is hard to read, and not suggestive of what is really going on, and if you add another preparatory assignment between the one for
t
and the value you want, you then need to change the2
to a3
, etc. In other words, this is a workaround/hack.A more elegant method is just to add a function called
let
that takes any number of arguments and returns its last one unchanged:and now you can write
let(t = floor((sqrt(1+8*n)-1)/2), n - (t+1)t/2)
and it looks and works the way you might expect. So I am opening this discussion to consider whether it is worth adding something likelet
from other languages into the mathjs expression language: either exactly this function, or a different syntax, say one modeled on Ocaml likelet t = Math.floor((Math.sqrt(1+8*n)-1)/2 in n - (t+1)t/2
.If there is some other existing way of doing this sort of thing that I have overlooked, I'd be happy to hear. I am aware you can write
t = floor((sqrt(1+8*n)-1)/2); n - (t+1)t/2
and that works, but it produces the answer wrapped in a ResultSet, and there are no facilities for manipulating that ResultSet or converting it into a value, within the mathjs expression language.Beta Was this translation helpful? Give feedback.
All reactions