ruby_object
ruby_object

Reputation: 1266

Haskell - how do I strip trailing spaces

I want to convert [1,2,3] to "1 2 3". at the moment I get "1 2 3 ". I import strip function using

import Data.Text (strip)

My code look like this:

ar2str ar = (concatMap (\x -> (show x)++" " ) ar)

How do I modify ar2str so that it works with strip?

Found it

http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Haskell

Rosetta Code to the rescue :-)

Upvotes: 1

Views: 497

Answers (2)

Adam Sosnowski
Adam Sosnowski

Reputation: 1284

Stripping trailing space makes sense if one processes given input strings. If one produces strings, its better just not to append the space in the first place. Especially that given the nature of Haskell lists, removing element from the end equals rebuilding the list.

Here's one way to achieve desired effect:

ar2str :: Show a => String -> [a] -> String
ar2str _ [x] = show x
ar2str sep (x:x':xs) = show x ++ sep ++ ar2str sep (x':xs)

Upvotes: 0

dfeuer
dfeuer

Reputation: 48591

You probably want to use Data.Text.unwords instead of all that. Or, if you're using String instead of Text, Data.List.unwords.

Upvotes: 5

Related Questions