Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forced strictness for lists in haskell

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?

like image 249
MaksymB Avatar asked Apr 05 '11 20:04

MaksymB


People also ask

What is strictness in Haskell?

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.

Are Haskell functions strict?

Haskell is a non-strict language, and most implementations use a strategy called laziness to run your program.

How are lists defined in Haskell?

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.

Can lists in Haskell have different types?

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?


2 Answers

(!) 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.

like image 158
Don Stewart Avatar answered Oct 26 '22 17:10

Don Stewart


seqList :: [a] -> ()
seqList [] = ()
seqList (x:xs) = strictList xs
like image 45
Curious George Avatar answered Oct 26 '22 18:10

Curious George