Are there any runtime costs for creating constants in a separate interface module like below? I guess the alternative would be to hardcode these where they are needed, but I feel this might be clearer and more maintainable.
interface Unicode
exposes [
Character,
utf8,
]
imports []
UnicodeCharacter : {
LF,
}
utf8 : UnicodeCharacter -> List U8
utf8 = \character ->
when character is
LF -> Str.toUtf8 "\u(000A)"
CR -> Str.toUtf8 "\u(000A)"
I feel like Roc could support space : List U8 = Str.toUtf8 "\u(0020)"
to define constants. Is this a bad idea?
Cost for the interface, no. Roc looks at the program holistically
As for your constant. I don't think it is a constant in current roc. I think roc will compile it into a top level thunk. So it will actually get called and be run. Sadly we don't have a comp time solutions here currently
Is it a bad idea, depends on your use case and how often that would get called. I don't know if we currently memoize top level thunks
There is a small change llvm will optimize it away, but probably not due to memory writes
Is there a way to make a constant in Roc? It would be sweet if we could use these in pattern matching, e.g.
EMPSACE : List U8 = [226, 128, 131]
when input is
[EMSPACE, ..] -> do somthing... # U+2003
I was doing the below which works well enough. Are there any runtime issues here?
emSpace = [226u8, 128u8, 131u8]
input = [226, 128, 131, 10, 1,2,3,4]
if List.startsWith input emSpace then
YES
else if List.startsWith input [10] then
OTHERS # just chain a lot of these together...
else
NOPE
Those will be proper constants that are directly ingested into the binary.
Well, emSpace
and input
will be.
I don't think the if and other functions would reduce down to constants, but actually not sure. It would totally depend on llvm optimizations, and my gut feeling is that llvm + lists = not optimized away
So i don't think it would compile the if to just always return YES
even though in theory that is just a constant expression.
In this example the input
would be variable and unknown, but it's good to know that emSpace
will be a constant. :+1:
eventually I'd like to do compile-time evaluation to make it so that all top-level declarations are either functions or statically allocated constants, but that's a ways off :big_smile:
Last updated: Jul 05 2025 at 12:14 UTC