title: Memoization of Intermediate Values In a Typeclass Instance
body: <p>I have the following function toTF that, given some context and an item, gives back a function that consumes a piece of input, an input state and produces the next state:</p>
  
  <pre><code>class TFSource s' where
      type S s' :: *
      type I s' :: *
      type O s' :: *
      toTF :: Context -&gt; s' -&gt; TFSig (S s') (I s') (O s')
  
  type TFSig s i o = [i] -&gt; s -&gt; Output s i o
  </code></pre>
  
  <p>The instance of this stuff for Token, which I am trying to implement, produces a function that applies the recognizers for the literal value of the token, its stem and part of speech, and, if all is well, accepts this token, otherwise fails.</p>
  
  <p>Here is my attempted instance declaration:</p>
  
  <pre><code>instance TFSource Token where
      toTF ctx (Token literal stem) = f
          where (litTF, stemTF) = (toTF ctx literal, toTF ctx stem)
                f (InputToken { .. } : ts) s = ... some computation ...
                f [] _ = Fail
  </code></pre>
  
  <p>How can I make sure that litTF and stemTF are shared (memoized?) across calls to toTF with the same values for ctx and the token?</p>