Stream: beginners

Topic: ✔ "Lazy" function to get expensive value


view this post on Zulip Johan Lindskogen (Dec 04 2023 at 08:26):

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

view this post on Zulip Luke Boswell (Dec 04 2023 at 08:27):

Use can use {} an empty record to make a thunk

view this post on Zulip Luke Boswell (Dec 04 2023 at 08:29):

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)

view this post on Zulip Johan Lindskogen (Dec 04 2023 at 08:36):

Oh, cool! I will try that! Thank you for the response!

view this post on Zulip Johan Lindskogen (Dec 04 2023 at 09:05):

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 }

view this post on Zulip Notification Bot (Dec 04 2023 at 09:05):

Johan Lindskogen has marked this topic as resolved.


Last updated: Jul 06 2025 at 12:14 UTC