Umair
Umair

Reputation: 685

How to write a Haskell function which inserts one space after every character of a string

I want to implement a method in Haskell which should add one space after every character of the string passed to that method, but not after the last character of that string.

For example:

Main> insertSpace "This is world"
"T h i s  i s  w o r l d"

Upvotes: -1

Views: 799

Answers (2)

Anton Kesy
Anton Kesy

Reputation: 832

Instead of intersperse, you could also use intercalate

import Data.List (intercalate)

insertSpace :: String -> String
insertSpace = intercalate " " . map (:[])

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54223

You could write this by hand through explicit recursion.

insertSpace :: String -> String
insertSpace []     = []
insertSpace (x:[]) = x  -- you need this to keep from adding a space at the end
insertSpace (x:xs) = x:' ':(insertSpace xs)

but there is a stdlib function for this in Data.List -- intersperse.

import Data.List (intersperse)

insertSpace :: String -> String
insertSpace = intersperse ' '

This is the first result when you search Hoogle for Char -> String -> String.

Upvotes: 5

Related Questions