# Memoizing example for learners

**URL:** <https://forums.swift.org/t/memoizing-example-for-learners/76585>\
**Category:** Using Swift\
**Tags:** memoizing\
**Created:** [December 13, 2024, 2:26am UTC](https://forums.swift.org/t/memoizing-example-for-learners/76585 "2024-12-13T02:26:16Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![ibex](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ibex/32/30439_2.png) [@ibex](https://forums.swift.org/u/ibex)\
**Post date:** [December 13, 2024, 2:26am UTC](https://forums.swift.org/t/memoizing-example-for-learners/76585/1 "2024-12-13T02:26:16Z")

</div>

I have found a little gem [here](https://forums.swift.org/t/advent-of-code-2024/76301/57).

@tevelee: Thank you for posting it.

```swift
// [https://forums.swift.org/t/advent-of-code-2024/76301/57]

func memoize <In: Hashable, Out> (_ f: @escaping (In) -> Out) -> (In) -> Out {
  var memo: [In: Out] = [:]
  return {
    if let result = memo[$0] {
      return result
    } else {
      let result = f($0)
      memo[$0] = result
      return result
    }
  }
}

```

Could an expert disect this function for the benefit of learners?

### Usage Example

```swift
func f (u:Int) -> String {
    "\(u)x\(u) = \(u * u)"
}

func g (u:Int) -> String {
    "\(u)x\(u)x\(u) = \(u * u * u)"
}

@main
struct Driver {
    static func main () {
        do {
            let u = memoize (f)
            
            print (u (2))
            print (u (2))
            print (u (2))
            print (u (7))
            print (u (7))
        }
        
        do {
            let u = memoize (g)
            
            print (u (2))
            print (u (2))
            print (u (2))
            print (u (7))
            print (u (7))
        }
    }
}

```

### Output

```swift
2x2 = 4
2x2 = 4
2x2 = 4
7x7 = 49
7x7 = 49
2x2x2 = 8
2x2x2 = 8
2x2x2 = 8
7x7x7 = 343
7x7x7 = 343

```

---

<div class="post-metadata">

**Author:** ![rayx](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/rayx/32/12204_2.png) [@rayx](https://forums.swift.org/u/rayx)\
**Post date:** [December 13, 2024, 2:43am UTC](https://forums.swift.org/t/memoizing-example-for-learners/76585/2 "2024-12-13T02:43:28Z")

</div>

> [@ibex](#):
>
> Could an expert disect this function for the benefit of learners?

The function returns a closure which captures `memo` variable. The variable serves a cache for past results. What's the part of the code you don't understand? Note `memo` is allocated in heap, that's why it can be accessed after `memoize()` returns.

---

<div class="post-metadata">

**Author:** ![taylorswift](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/taylorswift/32/43413_2.png) [@taylorswift](https://forums.swift.org/u/taylorswift)\
**Post date:** [December 13, 2024, 2:50am UTC](https://forums.swift.org/t/memoizing-example-for-learners/76585/3 "2024-12-13T02:50:01Z")

</div>

this is a cache access function that leverages `Dictionary`’s hashing implementation to track the precomputed values.

```swift
func memoize <In: Hashable, Out> 
    (_ f: @escaping (In) -> Out) -> (In) -> Out {
// ~~~~~~~~~~~~~~~~~~~~~~
// input function memoized function

```

the signature of `memoize` says it takes an input function of type `(In) -> Out`, and returns a modified version of that function of type `(In) -> Out`. in other words, they have the same type, which is a prerequisite for using `memoize(f)` as a drop-in replacement for `f`.

```swift
  var memo: [In: Out] = [:]

```

this line declares the backing storage of the memoized function. it’s a regular Swift [`Dictionary`](https://swiftinit.org/docs/swift/swift/dictionary). this will be captured by the returned function.

```swift
  return {
        ...
  }

```

this is the minimal syntax needed to declare a local function (as a closure literal). it could be written more explicitly like this

```swift
  return {
        (i:In) -> Out in
  }

```

but then you would lose the ability to use the `$0` abbreviation inside the closure body.

```swift
    if let result = memo[$0] {
// ~~~~~~~~~~~~~~~~~~~~~ Have we computed this value already?
      return result
    } else {
      let result = f($0)
// ~~~~~~~~~~~~~~~~~ Compute the value now...
      memo[$0] = result
// ~~~~~~~~~~~~~~~~~ Save the value in the Dictionary for the 
// next access...
      return result
    }

```

this is a dictionary cache access pattern. it could be written more efficiently like this

```swift
  return {
    (i: In) -> Out in {
      let value: Out = $0 ?? f(i)
      $0 = value 
      return value
    }(&memo[i])
  }

```

which would avoid re-hashing `In` twice, which may be expensive for a lot of real world types.

also, notice that `f` is captured in the closure, which means `f` will outlive the setup of `memoize`. thus, it must be annotated `@escaping`, since the closure itself will be returned, and the closure contains a reference to `f`.

the `memo` dictionary will also be captured, but in Swift, it does not need any annotations to allow this to happen.

---

<div class="post-metadata">

**Author:** ![taylorswift](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/taylorswift/32/43413_2.png) [@taylorswift](https://forums.swift.org/u/taylorswift)\
**Post date:** [December 13, 2024, 3:27am UTC](https://forums.swift.org/t/memoizing-example-for-learners/76585/5 "2024-12-13T03:27:23Z")

</div>

> [@rayx](#):
>
> Is the above text generated by ChatGPT? 😄

ChatGPT doesn’t do very well with code, but i asked GitHub Copilot and it gave me this:

> AI GENERATED CONTENT

* * *

This Swift function `memoize` is a higher-order function that takes a function `f` as an argument and returns a memoized version of that function. Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again.

Here's a step-by-step explanation:

1. **Function Signature** :

2. **Memo Dictionary** :

3. **Return Closure** :

This way, the `memoize` function ensures that the function `f` is only called once for each unique input, and subsequent calls with the same input return the cached result, improving performance for expensive or repetitive computations.

* * *

> END OF AI GENERATED CONTENT

this is a pretty good breakdown for a newcomer so i would say GitHub Copilot does a decent job of understanding the Swift cache access pattern.

the AI doesn’t do a good job of explaining the closure literal syntax, which looks a lot like the structural braces you would find in places like `if { } else { }` when placed in the position right after the `return`, but at least it parsed it correctly.

---

<div class="post-metadata">

**Author:** ![ibex](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ibex/32/30439_2.png) [@ibex](https://forums.swift.org/u/ibex)\
**Post date:** [December 13, 2024, 5:58am UTC](https://forums.swift.org/t/memoizing-example-for-learners/76585/6 "2024-12-13T05:58:06Z")

</div>

Thank you, @rayx, @taylorswift

This is an excellent example showing how closures can be used to create stateful functions.

---

<div class="post-metadata">

**Author:** ![jaleel](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jaleel/32/45076_2.png) [@jaleel](https://forums.swift.org/u/jaleel)\
**Post date:** [December 13, 2024, 8:18am UTC](https://forums.swift.org/t/memoizing-example-for-learners/76585/7 "2024-12-13T08:18:56Z")

</div>

As functions/closures are reference type, one could write it like:

```swift
class Memoise<In: Hashable, Out> {
  
  private var memo: [In: Out] = [:]
  let f: (In) -> Out
    
  init(f: @escaping (In) -> Out) {
    self.f = f
  }
  
  func `do`(_ input: In) -> Out {
    if let result = memo[input] {
      return result
    } else {
      let result = f(input)
      memo[input] = result
      return result
    }
  }
}

```

You can just do it same way using func/closures and currying.

---

<div class="post-metadata">

**Author:** ![tevelee](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tevelee/32/9775_2.png) [@tevelee](https://forums.swift.org/u/tevelee)\
**Post date:** [December 13, 2024, 9:55am UTC](https://forums.swift.org/t/memoizing-example-for-learners/76585/8 "2024-12-13T09:55:57Z")

</div>

Here's a variadic generic version of it that takes multiple parameters

> [@Trouble using a local func with parameter pack args](https://forums.swift.org/t/trouble-using-a-local-func-with-parameter-pack-args/76570/2):
>
> ```swift
> func memoize<each In: Hashable, Out>(_ factory: @escaping (repeat each In) -> Out) -> (repeat each In) -> Out {
> var memo: [Container<repeat each In>: Out] = [:]
> return { (pack: repeat each In) -> Out in
> let container = Container(repeat each pack)
> if let result = memo[container] {
> return result
> } else {
> let result = factory(repeat each pack)
> memo[container] = result
> return result
> }
> }
> }
> 
> private struct Container<each T> {
> let value: (repeat each T)
> 
> init(_ value: repeat each T) {
> self.value = (repeat each value)
> }
> }
> 
> extension Container: Equatable where repeat each T: Equatable {
> static func == (lhs: Container<repeat each T>, rhs: Container<repeat each T>) -> Bool {
> for (left, right) in repeat (each lhs.value, each rhs.value) {
> guard left == right else { return false }
> }
> return true
> }
> }
> 
> extension Container: Hashable where repeat each T: Hashable {
> func hash(into hasher: inout Hasher) {
> for element in repeat each value {
> hasher.combine(element)
> }
> }
> }
> 
> ```

---

<div class="post-metadata">

**Author:** ![CrystDragon](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/crystdragon/32/10461_2.png) [@CrystDragon](https://forums.swift.org/u/CrystDragon)\
**Post date:** [December 13, 2024, 11:08am UTC](https://forums.swift.org/t/memoizing-example-for-learners/76585/9 "2024-12-13T11:08:48Z")

</div>

You may want to check WWDC 2014 - session 404.  
Here's an archived video for you:  
[https://devstreaming-cdn.apple.com/videos/wwdc/2014/404xxdxsstkaqjb/404/404\_hd\_advanced\_swift.mov?dl=1](https://devstreaming-cdn.apple.com/videos/wwdc/2014/404xxdxsstkaqjb/404/404_hd_advanced_swift.mov?dl=1), the related content starts around 35:40.
