HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Function that produces \$a^nb^nc^n\$

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
functionthatproduces

Problem

I'm trying to write a function that produces an infinite list containing strings of the form \$a^nb^nc^n\$.

My first idea was to do it using comprehensions.

f = [replicate n 'a' ++ replicate n 'b' ++ replicate n 'c' | n <-[0..]]

But this does a lot of duplicate work. I then decided it would be better to do the following

import Data.List

f = "" : (abc "")

abc s = string : (abc string)
        where string = sort $ "abc" ++ s


How can I do this more efficiently without having to sort and use ++ as frequently? Would changing to ByteStrings help?

Solution

Your first solution could be more elegantly written as:

f :: [String]
f = [concatMap (replicate n) "abc" | n <- [0..]]


The basic operating principle would be the same, though.

A general sorting algorithm would be O(n log n) at best, so I don't believe that sort would be a good idea.

Code Snippets

f :: [String]
f = [concatMap (replicate n) "abc" | n <- [0..]]

Context

StackExchange Code Review Q#113541, answer score: 7

Revisions (0)

No revisions yet.