[Haskell-cafe] Re: [Haskell] lazy constructors

Serge D. Mechveliani mechvel at botik.ru
Wed Oct 13 06:24:12 EDT 2004


On Wed, Oct 13, 2004 at 10:06:44AM +0200, Sander Evers wrote:
> 
> >Question 2
> >----------
> >How to arrange the above `lazy' output?
> >  
> >
> Your function addToSPair
> 
> addToSPair :: Char -> (String, String) -> (String, String)
> addToSPair    c       (xs,     ys    ) =  (c:xs,   ys    )
> 
> does a strict pattern match on the pair constructor. It needs to know 
> that its second argument is a pair before it produces anything of its 
> result. If you use a lazy pattern match
> 
> addToSPair :: Char -> (String, String) -> (String, String)
> addToSPair    c       ~(xs,     ys    ) =  (c:xs,   ys    )
> 
> instead, it doesn't need to evaluate this argument immediately.


!!
This is great, thank you. This improves a lot.
I never recalled of the tilda for several years.

Excuse me for the stupidity, but I have a next naive question.

As the types are resolved before the computation, as the above
program shows,
how can  addToSPair  expect anything besides a string pair?
Why tilda is not a default?

--------------------------------------------- repeating: 
bottomStr :: String
bottomStr = let xs = xs in xs

bottomSPair :: (String, String)
bottomSPair = let p = p in p

longToReach = 10^8  :: Int 

f1, f2, g1, g2 :: Char

f1 = head ('a' :  (if last [1 .. longToReach] > 0 then "b" else "c"))
f2 = head ('a' : bottomStr)

addToSPair :: Char -> (String, String) -> (String, String)
addToSPair    c       (xs,     ys    ) =  (c:xs,   ys    )

g1 = head $ fst $ addToSPair 'a'
     (if  last [1 .. longToReach] > 0  then ("b", "") else ("c", ""))

g2 = head $ fst $ addToSPair 'a' bottomSPair
-----------------------------------------------------------------


The only doubt may be the matching of   (xs, ys)
against                                 bottom :: (String, String)
Is not this natural to have a result as
                               (bottom :: String, bottom :: String)
                                -- = xs           = ys
and compute further?
What will occur if all the Haskell programmers set `~' before each
data constructor in each pattern in their existing programs?
As the types are recognized before the computation, the programs
will remain safe and will become considerably faster.
For example, the above program of  g1  becomes a billion times
faster.
I wonder.

Copy, please, the answer to  mechvel at botik.ru

-----------------
Serge Mechveliani
mechvel at botik.ru













More information about the Haskell-Cafe mailing list