Is a memoization implementation in Haskell a monad?

I tried to solve Project Euler Problem 14 (including the length of the Collatz sequence) using memoization, and so I did to save the results of previous calculations. I have this function, collatzSequencewhich I want to remember, and I memoize it using computeWithMemo, which takes a function, the value to calculate the function on, Mapand returns the value of the function at this point and updated Map. Is that the image of a monad? Thanks!

import Data.Map                                                                   

computeWithMemo :: (Int -> Int) -> Int -> Map Int Int -> (Maybe Int, (Map Int Int)
computeWithMemo fun key memo                                                      
  | elem key (Data.Map.keys memo) = (Data.Map.lookup key memo, memo)              
  | otherwise = (Just (fun key), Data.Map.insert key (fun key) memo)              

collatzSequence :: Int -> Int                                                     
collatzSequence x                                                                 
  | x == 1 = 1                                                                    
  | even x = 1 + collatzSequence (x `div` 2)                                      
  | odd x = 1 + collatzSequence (x*3 + 1)                                         

memoize f = computeWithMemo f                                                     

memoizedCollatz = memoize collatzSequence                                         

solve x m                                                                         
  | x > 1 = solve (x-1) (snd (computeWithMemo (collatzSequence) x m))             
  | otherwise = m                                                                 

solution = solve 10000 Data.Map.empty                                             
+4
source share
1 answer

ad-hoc State , , , .

State :

  • solve.

    State >>= (bind), , ( ).

  • Int.

    State return, ( ).

  • , , , memoizing Map Int Int.

    State get, set modify , >>= , ( State, ).

, , !

, >>= return , , Monad, Haskell .

+1

Source: https://habr.com/ru/post/1618179/


All Articles