fuzion-lang.dev — The Fuzion Language Portal
JavaScript seems to be disabled. Functionality is limited.

memoize.fz


# This file is part of the Fuzion language implementation.
#
# The Fuzion language implementation is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, version 3 of the License.
#
# The Fuzion language implementation is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License along with The
# Fuzion language implementation.  If not, see <https://www.gnu.org/licenses/>.


# -----------------------------------------------------------------------
#
#  Tokiwa Software GmbH, Germany
#
#  Source code of Fuzion standard library feature memoize
#
# -----------------------------------------------------------------------


# memoize `f`.
# wraps f so that f will only be called once for every unique input.
#
# The term "memoization" was coined by Donald Michie in 1968 and
# is derived from the Latin word "memorandum" ("to be remembered"),
# usually truncated as "memo" in American English, and thus carries
# the meaning of "turning a function into something to be remembered".
# https://en.wikipedia.org/wiki/Memoization
#
# example:
#
#     mem := memoize (lock_free.Map i32 String) i32 String x->
#       say "computing $x"
#       x.as_string
#
#     say <| mem 1
#     say <| mem 2
#     say <| mem 1
#     say <| mem 3
#
#
public memoize(MM type : container.Mutable_Map T R, T type : property.equatable, R type, f T->R) T->R =>
  _ : Unary R T is

    # the memory
    store := MM.empty

    # implementation of abstract feature Unary.call
    #
    public redef call(a T) R =>
      # compute if not yet computed
      if store[a] = nil
        store.put a (f a)
      store[a].or_panic


# memoize the results of a function.
#
# example:
#
# say you have a function `fib` that performs poorly because it lacks
# memoization:
#
#     fib(n) =>
#       if n <= 1 then 1 else fib n-1 + fib n-2
#
# you can now memoize this as follows
#
#     fib(n) i32 : memoize => keep n _->
#       if n <= 1 then 1 else fib n-1 + fib n-2
#
# there are two things required: first, the function has to inherit from
# `memoize`.  Second, the body has to be wrapped into a call to `keep`
# with the key and a lambda to calculate the corresponding result, which
# would usually just wrap the original code.
#
# Apart from the speedup, the memoization shows up when you analyse the
# effects:
#
#     > ./build//bin/fz -effects fib.fz
#      ...
#     memoized_effect fib#1 i32 i32
#      ...
#
# It might be desired not to keep memoized results forever. To do so, we have
# to instate a local instance of the `memoize.memoized` effect. This can be
# done as follows:
#
#     # define my own memoization effect
#     my_fib_memo : memoize.memoized i32 i32 is
#
#     # create an instance of it and instate it
#     my_fib_memo ! ()->
#
#       # now use keep from this effect. Don not forget the `.env`!
#       fib2(n) => my_fib_memo.env.keep n _->
#         if n <= 1 then 1 else fib2 n-1 + fib2 n-2
#
#       # running this code shows improved performance
#       (40..45) .for_each (n->say "$n {fib2 n}")
#
# Since memoization is used locally only, the effect does not show up when
# effects are analysed.
#
#     > ./build//bin/fz -effects fib.fz
#      ...
#
# NOTE: Currently, memoization requires keys to be orderable. Would be great
#       to support hashable as well
#
# NOTE: Memoization is currently not thread safe. In case we want memoization
#       to be used among threads, we will need a thread safe variant. However,
#       this should currently be usable in multiple threads as long as each
#       thread has its own instance of memoized. We just do not profit from
#       values memoized in another thread.
#
public memoize is


  # effect wrapped around map of memoized keys and corresponding values
  #
  public memoized(# the key type, i.e, input type of memoized function
                  #
                  K type : property.orderable,

                  # the value type, i.e., result type of memoized function
                  #
                  V type
                  )
                  : effect
  is
    # the store used for memoization
    #
    # NYI: ENHANCEMENT: would be nice to also support property.hashable keys
    # using a tree map here
    #
    store := (container.ps_map K V).empty # (lock_free.Map K V).empty


    # use this memoized effect to retrieve the value for a given key or,
    # if that value was not calculated yet, calculate it
    #
    public keep(# the function input
                #
                k K,

                # the function to calculate the result
                #
                f K->V) V
    =>
      store[k].or_else ()->
        v := f k
        set store := memoized.this.env.store.put k v  # recursive calls to `f` may have replaced `memoized.this.env.store`!
        memoized.this.replace
        v


  # use global memoized effect to retrieve the value for a given key or,
  # if that value was not calculated yet, to return it
  #
  public keep(# the key type, i.e, input type of memoized function
              #
              K type : property.orderable,

              # the value type, i.e., result type of memoized function
              #
              V type,

              # the function input
              #
              k K,

              # the function to calculate the result
              #
              f K->V
              ) V
  =>
    (memoized_effect memoize.this K V).env.keep k f


  # For memoization of constant values that do not depend on any input, this
  # uses the global constant memoization effect to keep that value
  #
  # Use this as follows: Say you have an expensive function like this that
  # approximates pi:
  #
  #     pi =>
  #       (4.0 :: (-)).zip (1.0 :: +2) (/)   # 4/1, -4/3, 4/5, -4/7, ...
  #                   .take 10000
  #                   .sum
  #
  # You can memoize the result as follows
  #
  #     pi : memoize =>
  #       const ()->
  #         (4.0 :: (-)).zip (1.0 :: +2) (/)   # 4/1, -4/3, 4/5, -4/7, ...
  #                     .take 10000
  #                     .sum
  #
  # Then, repeated calls to `pi` will result in returning the pre-calculated value.
  #
  # Effects analysis of this code will show that it uses
  #
  #   memoized_constant_effect pi f64
  #
  public const(# the value type, i.e., result type of memoized function
              #
              V type,

              # the function to calculate the result
              #
              f ()->V
              ) V
  =>
    (memoized_constant_effect memoize.this V).env.const f


# effect to memoize values calculated from given keys.
#
# This effect uses a global lock to ensure consistency. However, this global
# lock is used at most once for each key/value pair used by each thread.  On
# the first access to a key, a local copy of the global store is made such that
# future accesses using the same key will find the value on the local store.
#
memoized_effect(# type to identify this memoized instance
                #
                M type,

                # the key type, i.e, input type of memoized function
                #
                K type : property.orderable,

                # the value type, i.e., result type of memoized function
                #
                V type,

                # the store used for memoization
                #
                # NYI: ENHANCEMENT: would be nice to also support property.hashable keys
                # using a tree map here
                 #
                store container.ps_map K V,

                # ref containing the mutatble global value, accessed while
                # `memoize_mutate.env.exclusive`.
                #
                global Ref (memoize_mutate.var (container.ps_map K unit),  # map that is set for key k if a thread started calculating k's value.
                            memoize_mutate.var (container.ps_map K V   )   # map of all calculated values
                            )
               )
  : effect
is

  # use this memoized effect to retrieve the value for a given key or,
  # if that value was not calculated yet, calculate it
  #
  public keep(# the function input
              #
              k K,

              # the function to calculate the result
              #
              f K->V) V
  =>
    memoized_effect.this.env.store[k].or_else ()->
      m := memoize_mutate.env.exclusive_when (() -> !global.v.0[k] || (global.v.1[k]??)) ()->  # run when calculation for k has not started or it has finished
                                 gm := global.v.1.get
                                 if gm[k]?? then
                                   option gm
                                 else
                                   global.v.0 <- global.v.0.put k unit
                                   nil
                             .or_else ()->
                               v := f k                     # note that we call `f()` while not exclusive
                               global.v.1.update (.put k v) # use `global.v.update` since it is exclusive, unlike `global <-`
                                         .1                 # return updated map
      (memoized_effect M K V m global).replace
      m[k]!


  # default implementation of memoized_effect
  #
  # this will get instated automatically at startup
  #
  public redef fixed type.default_value option (memoized_effect M K V)
  =>
    m1 := container.ps_map K unit .empty
    m2 := container.ps_map K V    .empty
    memoized_effect M K V m2 (Ref (memoize_mutate.env.var m1,
                                   memoize_mutate.env.var m2))


# a blocking mutate that is used to memoize values globally, i.e., for all threads
#
memoize_mutate : concur.blocking_mutate is

  public redef fixed type.default_value option memoize_mutate
  =>
    memoize_mutate


calculating is

global_value(V type) : choice nil         # no value available yet
                              calculating # some thread is calculating the value
                              V           # the value
is
  busy =>
    match global_value.this
      calculating => true
      *           => false

# ref type wrapped around mutable `global_value`
#
Ref(V type, v V) ref is


# effect to memoize constant values calculated only once
#
private:public memoized_constant_effect(# type to identify this memoized instance
                                        #
                                        M type,

                                        # the value type, i.e., result type of memoized function
                                        #
                                        V type,

                                        # the stored value, accessed by current thread only, so no
                                        # need for exclusivity
                                        store option V,

                                        # ref containing the mutatble global value, accessed while
                                        # `memoize_mutate.env.exclusive`.
                                        #
                                        global Ref (memoize_mutate.var (global_value V))
                                        )
  : effect
is

  # use this memoized effect to retrieve the value or,
  # if it was not calculated yet, calculate it
  #
  public const(# the function to calculate the result
               #
               f ()->V
               ) V
  =>
    memoized_constant_effect.this.env.store.or_else ()->
      v := memoize_mutate.env.exclusive_when (() -> !global.v.busy) ()->
                               match global.v.get
                                 v1 V => option v1
                                 *    => global.v <- calculating
                                         nil
                             .or_else ()->
                               v2 := f()                   # note that we call `f()` while not exclusive
                               _ := global.v.update _->v2  # use `global.v.update` since it is exclusive, unlike `global <-`
                               v2
      (memoized_constant_effect M V v global).replace
      v

  # default implementation of memoized_constant_effect
  #
  # this will get instated automatically at startup
  #
  public redef fixed type.default_value option (memoized_constant_effect M V)
  =>
    memoized_constant_effect M V nil (Ref (memoize_mutate.env.var (global_value V) nil))

last changed: 2026-11-05