Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning Haskell: String manipulation question

Tags:

string

haskell

How can I write a function in Haskell, that takes an input string in the format a1a2a3 and expands into a1a2a2a3a3a3. For example input string "code" would be expanded into "coodddeeee"

like image 565
BM. Avatar asked Jan 24 '10 11:01

BM.


1 Answers

So you want the nth character repeated n times.

f :: String -> String
f x = concatMap g  (zip x [1..])
   where
       g (x,y) = replicate y x

I'm sure there's an easier way to do this.

Explanation: First we get the string and pair it with it's place in the list (starting at 1). This is what zip does:

Prelude> zip "code" [1..]
[('c',1),('o',2),('d',3),('e',4)]

Now the function g (x,y) uses the replicate function which replicates whatever you want y times. So we replicate x, y times.

Prelude> g ('z',4)
"zzzz"

If we map this function over the list produced you get the result:

Prelude> map g $ zip "code" [1..]
["c","oo","ddd","eeee"]

If you have a list of strings, you can concatenate them together using concat. concatMap applies the function g to each pair of letter and number and then concatenates the string into the final result.

Prelude> concat $ map g $ zip "code" [1..]
"coodddeeee"

Basically: concat $ map g -> concatMap g

EDIT: now it works, it can also be done in one line thusly:

f x = concatMap (\(a,b)->replicate b a ) $ zip x [1..]

Output:

Prelude> f "lambda"
"laammmbbbbdddddaaaaaa"
like image 184
Jonno_FTW Avatar answered Sep 28 '22 08:09

Jonno_FTW