Reputation: 5681
For learning Haskell (nice language) I'm triying problems from Spoj.
I have a table with 19000 elements all known at compile-time. How can I make the table strict with 'seq'? Here a (strong) simplified example from my code.
import qualified Data.Map as M
-- table = M.fromList . zip "a..z" $ [1..] --Upps, incorrect. sorry
table = M.fromList . zip ['a'..'z'] $ [1..]
Upvotes: 4
Views: 1642
Reputation: 139890
I think you're looking for deepseq
in Control.DeepSeq
which is used for forcing full evaluation of data structures.
Its type signature is deepseq :: NFData a => a -> b -> b
, and it works by fully evaluating its first argument before returning the second.
table = t `deepseq` t
where t = M.fromList . zip ['a'..'z'] $ [1..]
Note that there is still some laziness left here. table
won't get evaluated until you try to use it, but at that point the entire map will be evaluated.
Note that, as luqui pointed out, Data.Map
is already strict in its keys, so doing this only makes sense if you want it to be strict in its values as well.
Upvotes: 5
Reputation: 36349
The general answer is, you write some code that must force evaluation of the whole datastructure. For example, if you have a list:
strictList xs = if all p xs then xs else []
where p x = x `seq` True
I am sure there is already some type class that would apply such forcing recursively and instances for standard data types.
Upvotes: 3