Michael
Michael

Reputation: 83

Converting a list of letters into a word (and removing speech marks)

Does anyone know of a way in Haskell to convert something in the form

["w","o","r","d"]

into

word

I have just finished my very first program (an RSA encryption) and the output at the moment is really ugly. I'm sorry if this is a really silly question but I really have no idea of how to go about it. Also, to make my input a lot easier, does anyone know of a way to convert

word

into

[w,o,r,d]

Upvotes: 1

Views: 500

Answers (4)

mhwombat
mhwombat

Reputation: 8136

Even if you've never heard of "concat", here's how you can solve this type of problem. Let's figure out what type you have:

λ> :t ["w","o","r","d"]
["w","o","r","d"] :: [[Char]]

OK, so that's a list of lists of Chars.

Now let's figure out the type you want:

λ> :t "word"
"word" :: [Char]

So we want a function that converts list of lists of Chars to simple lists of Chars. In other words, we want a function with the signature [[Char]] -> [Char]. Let's search for a function with that type signature* using Hoogle. Doing that just now, the fourth function in the list was:

concat :: [[a]] -> [a]
base Prelude, base Data.List
Concatenate a list of lists. 

That's exactly what we want.

  • Better yet, you might have realised that the operation we need could operate with lists of any type. Then you would search for the type signature [[a]] -> [a]. (This sort of insight comes with practice.) When I did that just now, concat was the first result.

Upvotes: 10

bheklilr
bheklilr

Reputation: 54058

As others have said, concat is the way to go for converting a [[Char]] into [Char], as for going the other way, you have two options. You can treat your string "word" as the list of Chars it is (remember, it's type is String, which is just an alias for [Char]) and just operate on Chars instead of Strings, or you can convert each single character into a single-character String. I recommend the former, but I'll demonstrate the other as well.

The easiest way to do this is with a very simple list comprehension. All you have to do is get each letter from the word, and wrap it in [] to make it a list. Since String = [Char], you get each letter of the word as a String.

splitUpWord :: String -> [String]
splitUpWord word = [[letter] | letter <- word]

Upvotes: 2

sfjac
sfjac

Reputation: 7294

Look at concat. You have a list of lists of chars. Flattening this is a common pattern and concat is the tool to do it. That said, if you're learning you might give it a go yourself.

Upvotes: 1

Don Stewart
Don Stewart

Reputation: 137947

Check the types:

Prelude> let s = ["w","o","r","d"]
Prelude> :t s
s :: [[Char]]

So you can treat it as a list of lists of characters.

What function "flattens" lists? concat:

Prelude> :t concat s
concat s :: [Char]

So that's our string, and we print it with putStrLn

Prelude> putStrLn  $ concat s
word

Upvotes: 5

Related Questions