Okay this is really a beginner question. But I'm stumped.
I can't figure out how to assign variables within the scope of a function.
I get that I can do foobar = "foobar"
to assign module-scoped constants
but what if I want to do an expensive operation on runtime data, and use the result in two different places?
basically I wanted to do something like
let
a = f x
in
(g a) + (h a)
I can of course do
(g (f x)) + (h (f x))
but that seems to compute f
twice? Seems really inefficient.
I assume that I'm just being dumb here and need some help :innocent:
I of course read through the tutorial. It seems the most relevant section was "Naming things", but that only describes assigning constants.
I guess I could "fork" the value by calling a function like \a -> (g a) + (h a)
Is that maybe the idiomatic way to do this?
ah! Short answer is to take your let
... in
example and delete the let
and in
keywords :smiley:
here's an example in the tutorial: https://www.roc-lang.org/tutorial#if-then-else
basically Roc uses let
... in
semantics except it's based on indentation instead of having actual let
and in
keywords
Also doesn't Roc have some magic compiler stuff so that calling the function twice with the same argument is zero additional work? It's not being calculating things again right?
not currently, although theoretically we could in certain cases
Ah cool. Thanks for the help.
A suggestion: maybe it would be useful to include a non-constant assignment example in the "Naming things" section. :)
Last updated: Jul 06 2025 at 12:14 UTC