Skip to content

Commit

Permalink
Add some solutions and hints for fibonacci exercises
Browse files Browse the repository at this point in the history
  • Loading branch information
bbannier committed Jun 12, 2024
1 parent 6e15bf2 commit 989881a
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions src/functions_exercises.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,22 @@

For testing you can `assert fib(8) == 21;`.

<details>
<summary>Solution</summary>

```spicy
function fib(n: uint64): uint64 {
if (n < 2)
return n;
# This runs iff above `if` condition was false, but in this case could also be written
# as an `else` branch.
return fib(n - 1) + fib(n - 2);
}
```

</details>

1. Add memoization to your `fib` function. For that change its signature to

```spicy
Expand All @@ -27,5 +43,51 @@

For testing you can `assert fib(64, m_fib) == 10610209857723;`.

<details>
<summary>Solution</summary>

```spicy
function fib(n: uint64, inout cache: map<uint64, uint64>): uint64 {
# If the value is already in the cache we do not need to compute it.
if (n in cache)
return cache[n];
# Value was not in the cache. Compute its value and store it.
local result = 0;
if (n < 2)
result = n;
else
# Here we want an `else` branch for sure. We need to pass the cache
# down to other invocations. Since the passing happens by reference all
# invocations share a cache.
result = fib(n - 1, cache) + fib(n - 2, cache);
# Persist result in cache.
cache[n] = result;
# Return the result.
return result;
}
```

</details>

1. Try modifying your `fib` functions so users do not have to provide the cache
themselves.

<details>
<summary>Hint</summary>

You want to store the cache somewhere yourself and provide users with a
wrapped function which implicitly uses your cache.

There are two places to put the cache:

- Construct the cache as a local variable inside the body of your wrapper
function. With this different invocations of the wrapper function would
not share the same cache which can be useful in certain scenarios.
- Alternatively one could store the cache in a `global`.

</details>

0 comments on commit 989881a

Please sign in to comment.