ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Functional Caching with Memoization

Haskell

Goal -- WPM

Ready
Exercise Algorithm Area
1module FunctionalCaching where
2
3import qualified Data.Map as Map
4import Data.IORef -- Using IORef for a mutable cache in IO context for simplicity
5import System.IO.Unsafe (unsafePerformIO) -- For a global mutable cache (use with caution)
6
7-- | A type for our memoization cache, mapping input to output.
8type Cache k v = Map.Map k v
9
10-- | A global mutable cache for demonstration purposes.
11-- In a real-world scenario, you might pass the cache explicitly or use a Reader monad.
12{-# NOINLINE globalCacheFactorial #}
13globalCacheFactorial :: IORef (Cache Int Integer)
14globalCacheFactorial = unsafePerformIO $ newIORef Map.empty
15
16-- | Computes the factorial of a non-negative integer using memoization.
17-- This version uses a global mutable cache managed via IORef and unsafePerformIO.
18factorialMemoized :: Int -> Integer
19factorialMemoized n
20| n < 0 = error "Factorial is not defined for negative numbers"
21| n == 0 = 1
22| otherwise = unsafePerformIO $ do
23cache <- readIORef globalCacheFactorial
24case Map.lookup n cache of
25Just result -> return result -- Return cached result
26Nothing -> do
27-- Compute the result recursively
28let result = fromIntegral n * factorialMemoized (n - 1)
29-- Update the cache with the new result
30writeIORef globalCacheFactorial (Map.insert n result cache)
31return result
32
33-- | A pure version of factorial for comparison (without caching).
34pureFactorial :: Int -> Integer
35pureFactorial n
36| n < 0 = error "Factorial is not defined for negative numbers"
37| n == 0 = 1
38| otherwise = fromIntegral n * pureFactorial (n - 1)
39
40-- | Main function to demonstrate functional caching.
41main :: IO ()
42main = do
43putStrLn "--- Functional Caching Demo (Factorial) ---"
44
45let num = 10
46putStrLn $ "Calculating factorial of " ++ show num ++ " (pure):"
47let factPure = pureFactorial num
48print factPure
49
50putStrLn $ "\nCalculating factorial of " ++ show num ++ " (memoized):"
51let factMemo1 = factorialMemoized num
52print factMemo1
53
54putStrLn $ "\nCalculating factorial of " ++ show num ++ " again (memoized):"
55-- This call should be faster as the result is cached.
56let factMemo2 = factorialMemoized num
57print factMemo2
58
59let largeNum = 20
60putStrLn $ "\nCalculating factorial of " ++ show largeNum ++ " (memoized):"
61let factLargeMemo = factorialMemoized largeNum
62print factLargeMemo
63
64-- Edge case: factorial of 0
65putStrLn "\nCalculating factorial of 0 (memoized):"
66print $ factorialMemoized 0
67
68-- Edge case: factorial of 1
69putStrLn "Calculating factorial of 1 (memoized):"
70print $ factorialMemoized 1
71
72-- Demonstrating cache state (optional, for inspection)
73finalCache <- readIORef globalCacheFactorial
74putStrLn $ "\nFinal cache state: " ++ show (Map.size finalCache) ++ " entries."
Algorithm description viewbox

Functional Caching with Memoization

Algorithm description:

This Haskell code implements memoization for the factorial function, a common technique for functional caching. It uses a global `IORef` holding a `Map` to store previously computed results. When `factorialMemoized` is called, it first checks the cache. If the result is found, it's returned directly; otherwise, it computes the result, stores it in the cache, and then returns it. This significantly speeds up repeated calculations of the same values, essential for performance in recursive algorithms like dynamic programming or complex computations.

Algorithm explanation:

The `factorialMemoized` function computes factorials while using a cache. It first checks for base cases (`n < 0` or `n == 0`). If `n` is positive, it looks up `n` in the `globalCacheFactorial`. If found, the cached `result` is returned. If not found, the factorial is computed recursively (`fromIntegral n * factorialMemoized (n - 1)`), the `result` is inserted into the cache using `writeIORef`, and then returned. The use of `unsafePerformIO` and `{-# NOINLINE #-}` is a common (though potentially dangerous) pattern to create a global mutable cache that appears pure from the outside. For pure functional caching without `unsafePerformIO`, one would typically pass the cache explicitly as an argument and return it along with the result, or use a state monad. The time complexity for the first calculation of `factorialMemoized n` is O(n) because each value from 0 to n is computed once. Subsequent calls for values already computed are O(1) due to cache lookup. Space complexity is O(n) to store the computed factorials up to `n` in the cache.

Pseudocode:

define Cache as a Map from key (Int) to value (Integer)

define globalCacheFactorial as a mutable reference to a Cache, initialized as empty

function factorialMemoized(n):
  if n is less than 0:
    throw error
  else if n is 0:
    return 1
  else:
    read the current cache from globalCacheFactorial
    if n is in the cache:
      return the cached value for n
    else:
      compute result = n * factorialMemoized(n - 1)
      insert (n, result) into the cache
      write the updated cache back to globalCacheFactorial
      return result

function pureFactorial(n):
  if n is less than 0:
    throw error
  else if n is 0:
    return 1
  else:
    return n * pureFactorial(n - 1)

main:
  calculate factorial of 10 using pureFactorial and print
  calculate factorial of 10 using factorialMemoized and print
  calculate factorial of 10 again using factorialMemoized and print (should be faster)
  calculate factorial of 20 using factorialMemoized and print
  calculate factorial of 0 using factorialMemoized and print
  calculate factorial of 1 using factorialMemoized and print
  print the size of the global cache