I made really time consuming algorithm which produces a short string as the result. When I try to print it (via putStrLn) it appears on the screen character by character. I did understand why that happened, and I tried to force evaluation of the string before actual printing.
myPrint !str = putStrLn str
But this help very little. When I ran the program in debug I noticed that the !str forced evaluation only for the first character.
Does anyone know why is that, and how to deal with this?
Function arguments A function is considered strict in one of its arguments if, when the function is applied to a bottom value for that argument, the result is bottom.
Haskell is a non-strict language, and most implementations use a strategy called laziness to run your program.
In Haskell, lists are a homogenous data structure. It stores several elements of the same type. That means that we can have a list of integers or a list of characters but we can't have a list that has a few integers and then a few characters.
One is of type (String,Int) , whereas the other is (Int,String) . This has implications for building up lists of tuples. We could very well have lists like [("a",1),("b",9),("c",9)] , but Haskell cannot have a list like [("a",1),(2,"b"),(9,"c")] . Which of these are valid Haskell, and why?
(!)
translates into seq
, which evaluates strictly to Weak Head Normal Form -- that is, it only evaluates to the outermost constructor. To evaluate more deeply, you need a "deep" form of seq
.
This is known as deepseq
.
It is in the deepseq package.
seqList :: [a] -> ()
seqList [] = ()
seqList (x:xs) = strictList xs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With