lazy evaluation - How do I force a function to be called immediately in Haskell? -


this code:

import data.function.memoize import debug.trace  foo :: int -> int -> int foo = memofix foomemo      foomemo f x = + (trace (show x) cont)         cont = if x == 0 0 else x + f (x - 1)  main =     print $ foo 0 5     print $ foo 0 5     print $ foo 0 5 

i expected print:

3 2 1 0 6 6 6 

but, instead, prints this:

3 2 1 0 6 3 2 1 0 6 3 2 1 0 6 

in other words, function not memoized expected be. because each time "foo 0" called, new memo-table created "foo". how can force ghc evaluate "memofix foomemo" once, doesn't create more 1 memotable?

the problem memotable created each parameter value, foo 0 etc., not whole of foo. , memotables not shared 1 invocation of foo next. solution make sure also memoize whole of foo:

import data.function.memoize import debug.trace  foo :: int -> int -> int foo = memoize foo1     foo1 = memofix foomemo          foomemo f x = + (trace (show x) cont)             cont = if x == 0 0 else x + f (x - 1)  main =     print $ foo 0 5     print $ foo 0 5     print $ foo 0 5 

btw find following way of writing easier using memofix:

foo :: int -> int -> int foo = memoize2 $ \a x ->     let cont = if x == 0 0 else x + foo (x - 1)     in + (trace (show x) cont) 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -