QSpider
QSpider

Reputation: 577

Solve a memoization in Haskell

I wrote data type and instance Monad class. Below is my source code:

data UI a = UI { unUI :: a } 
             deriving Functor


instance Applicative UI where
    pure   = UI
    m *>  k = m >>= \ _ -> k
    m <*  k = m >>= \ _ -> m
    m <*> k = UI $ (unUI m) (unUI k)


instance Monad UI where
    m >>  k = m >>= \ _ -> k
    m >>= k = k $ unUI m
    return  = UI

But, when i use function like below:

generateUUID :: UI String
generateUUID = do 
    ruuid <- liftIO $ UV4.nextRandom
    return $ UV.toString ruuid

I encounter problems with memoization! Is it poosible to do something?

Upvotes: 0

Views: 96

Answers (1)

jakubdaniel
jakubdaniel

Reputation: 2223

By using unsafePerformIO to hide the presence of effects in IO actions you are deliberately (and most probably illegally) entering the realm of pure functions. In that realm it is allowed to memoize / refactor. The compiler will usually try to use the purity to full extent to avoid redundant work in runtime. Is there a real reason why you would hide the impurity, especially in something called UI, where one can expect interaction with outside world (human)? This could indicate bad design. Your UI seems to be the same as Identity which is the simplest functor without any impure effects.

Upvotes: 5

Related Questions