Stream: beginners

Topic: Variable assignments? No let...in?


view this post on Zulip Asbjørn Olling (Dec 01 2023 at 11:29):

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.

view this post on Zulip Asbjørn Olling (Dec 01 2023 at 11:32):

I assume that I'm just being dumb here and need some help :innocent:

view this post on Zulip Asbjørn Olling (Dec 01 2023 at 11:33):

I of course read through the tutorial. It seems the most relevant section was "Naming things", but that only describes assigning constants.

view this post on Zulip Asbjørn Olling (Dec 01 2023 at 11:33):

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?

view this post on Zulip Richard Feldman (Dec 01 2023 at 11:38):

ah! Short answer is to take your let ... in example and delete the let and in keywords :smiley:

view this post on Zulip Richard Feldman (Dec 01 2023 at 11:38):

here's an example in the tutorial: https://www.roc-lang.org/tutorial#if-then-else

view this post on Zulip Richard Feldman (Dec 01 2023 at 11:39):

basically Roc uses let ... in semantics except it's based on indentation instead of having actual let and in keywords

view this post on Zulip Luke Boswell (Dec 01 2023 at 11:41):

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?

view this post on Zulip Richard Feldman (Dec 01 2023 at 11:43):

not currently, although theoretically we could in certain cases

view this post on Zulip Asbjørn Olling (Dec 01 2023 at 11:52):

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