Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a table (Data.Map) strict in haskell?

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..]
like image 788
Jogusa Avatar asked Feb 25 '23 05:02

Jogusa


1 Answers

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.

like image 75
hammar Avatar answered Mar 03 '23 18:03

hammar