[Haskell-cafe] functions making their own memos

Dennis Raddle dennis.raddle at gmail.com
Sun Jul 8 06:42:14 UTC 2018


I've been wondering for some time how to handle a common use case in
imperative programming, "static" variables that are accessed only inside
one function, but not needed elsewhere.

I think this probably has something to do with existential quantification,
but in any case this is an area I'm ready to learn a lot more about. Any
ideas are welcome along with suggested reading.

Let's say that I have a function for generating random numbers every time
it is called, but I sometimes want it to to re-use the last number
depending on the time the last number was geneated:

sometimesNew :: Time -> Int -> IO (Time,Int)
sometimesNew lastTime lastValue = do
  currentTime <- <get time for system>
  if currentTime > lastTime + 10
    then do
      newValue <- <get pseudorandom value>
      return (currentTime,newValue)
    else return (lastTime,lastValue)

This function depends on the caller to remember its output (last time and
last value) and feed that back to it.

It would be nice if this function could make some kind of memo inside it
itself and no one else needs to know.

The case I'm working on right now is doing animation in Purescript on a
canvas, in which I can control the motion of an object appearing in the
animation by composing functions that control the motion. I might like to
write a function that generates an overall circular trajectory, then
compose it with a function that generates a slight wobbly motion. The
wobbly function needs, basically, to change the motion randomly by
interpolating between random positions and changing the random position
only occassionally instead of during every animation frame.

type MovementFunc = ...

So this would generate a large circular movement:

circularMovement :: MovementFunc

This generates a small wobble.

wobble :: MovementFunc

Then I can compute the final position once per animation frame by
superimposing or composing individual movements:

computePosition :: [MovementFunc] -> Time -> IO Position

The wobble function might like to have access to a memo of the last
randomly chosen position, and how long ago in milliseconds it chose that
position.

Let's say that every movement function might like to have access to a memo,
but the actual data type involved could be different from function to
function. I also need to deal with initializing the memo. So the trick is
to maintain and initialize these memo types without needing to know the
internals of every function.

Dennis
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20180707/0b63f09d/attachment.html>


More information about the Haskell-Cafe mailing list