Why does length return 1 for a tuple with 2 elements, and gives an error for a tuple with more elements?

You have encountered a Haskell cause célèbre that has sparked much discussion and gnashing of teeth. Basically, for the purposes of Foldable (the typeclass that provides length), 2-tuples are not considered a container of two elements, but a container of one element accompanied by some context. You can extract a list of elements of type … Read more

Positive integer type

module Positive (toPositive, getPositive, Positive) where newtype Positive = Positive { unPositive :: Int } toPositive :: Int -> Maybe Positive toPositive n = if (n <= 0) then Nothing else Just (Positive n) — We can’t export unPositive, because unPositive can be used — to update the field. Trivially renaming it to getPositive — … Read more

Writing foldl using foldr

Some explanations are in order! What is the id function for? What is the role of? Why should we need it here? id is the identity function, id x = x, and is used as the equivalent of zero when building up a chain of functions with function composition, (.). You can find it defined … Read more

What’s so bad about Lazy I/O?

Lazy IO has the problem that releasing whatever resource you have acquired is somewhat unpredictable, as it depends on how your program consumes the data — its “demand pattern”. Once your program drops the last reference to the resource, the GC will eventually run and release that resource. Lazy streams are a very convenient style … Read more