Hi, I am trying to make a helper function to lookup a value or lazyly calculate it if the key is not present in the cache.
Is it possible to make a function with bound parameters but not call it until later?
This is what I got so far:
getOrCalculate: Dict a b, a, (() -> b) -> b
getOrCalculate = \cache, id, calculateFn ->
when Dict.get id is
Ok v ->
{ cache, value: v }
Err KeyNotFound ->
v = calculateFn
{ cache: Dict.insert cache id v, value: v }
and it fails because ()
is not the right way to type "a function with no parameters", but how do I make it not be just a const?
I am partway through parsing a parenthesized type:
48│ getOrCalculate: Dict a b, a, (() -> b) -> b
Use can use {}
an empty record to make a thunk
Try
getOrCalculate: Dict a b, a, ({} -> b) -> (Dict a b, b)
getOrCalculate = \cache, id, calculateFn ->
when Dict.get cache id is
Ok v -> (cache, v)
Err KeyNotFound ->
v = calculateFn {}
(Dict.insert cache id v, v)
Oh, cool! I will try that! Thank you for the response!
Works as a charm! This is what I ended up with!
getOrCalculate : Dict a b, a, ({} -> b) -> { updatedCache : Dict a b, value : b }
getOrCalculate = \cache, id, calculateFn ->
when Dict.get cache id is
Ok v ->
{ updatedCache: cache, value: v }
Err KeyNotFound ->
v = calculateFn {}
{ updatedCache: Dict.insert cache id v, value: v }
Johan Lindskogen has marked this topic as resolved.
Last updated: Jul 06 2025 at 12:14 UTC