Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

space leak in simple string generation. why?

Tags:

haskell

-- generates names in the following order
-- a, b, c ... z, aa, ba, ca, ... za, ab, bb, cb ...
nextName :: String -> String
nextName [] = "a"
nextName (x:xs) = if x == 'z' then 'a' : nextName xs else succ x : xs

-- verify if the number of names generated is as expected.
countNames :: String -> String -> Int
countNames start end = loop 1 start
    where
        loop acc next =
            if next == end then
                acc
            else
                loop (acc + 1) (nextName next)

run countNames "a" "zzzzzz" in ghci

running it on my com takes up the whole of the memory and takes a hell of lot of time to complete.

appreciate it if anyone indicate where and why space leak is happening?

like image 657
santosh Avatar asked Feb 04 '26 17:02

santosh


1 Answers

The problem is a large counter thunk because loop is not strict on the counter acc. The usual solution is to use seq or BangPatterns to make it strict. Here is the solution using BangPatterns.

{-# LANGUAGE BangPatterns #-}
-- generates names in the following order
-- a, b, c ... z, aa, ba, ca, ... za, ab, bb, cb ...
nextName :: String -> String
nextName [] = "a"
nextName (x:xs) = if x == 'z' then 'a' : nextName xs else succ x : xs

-- verify if the number of names generated is as expected.

countNames :: String -> String -> Int
countNames start end = loop 1 start
    where
        loop !acc next =
            if next == end then
                acc
            else
                loop (acc + 1) (nextName next)
like image 179
Satvik Avatar answered Feb 06 '26 08:02

Satvik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!