
Thank you for your response Edward, You write that it is usually only evaluated once, do you know the circumstances under which it is evaluated more than once? I have some examples of this but they are all very large. The real issue I was having was actually not with a list but with a memoised function i.e. something like:
class C a where memoised :: Int -> a <<<
Perhaps functions are treated differently?
Regards,
Jonas
On 29 June 2012 15:55, Edward Z. Yang
Hello Jonas,
Like other top-level definitions, these instances are considered CAFs (constant applicative forms), so these instances will in fact usually be evaluated only once per type X.
import System.IO.Unsafe class C a where dflt :: a instance C Int where dflt = unsafePerformIO (putStrLn "bang" >> return 2) main = do print (dflt :: Int) print (dflt :: Int) print (dflt :: Int)
ezyang@javelin:~/Dev/haskell$ ./caf bang 2 2 2
Cheers, Edward
Excerpts from Jonas Almström Duregård's message of Fri Jun 29 07:25:42 -0400 2012:
Hi,
Is there a way to ensure that functions in a class instance are treated as top level definitions and not re-evaluated?
For instance if I have this:
class C a where list :: [a]
instance List a => List [a] where list = permutations list <<< How can I ensure that list :: [[X]] is evaluated at most once for any type X (throughout my program)?
I assume this is potentially harmful, since list can never be garbage collected and there may exist an unbounded number of X's.
I currently have a solution that uses Typeable to memoise the result of the function based on its type. Is there an easier way?
Regards, Jonas