Home > Enterprise >  String to [Char] in haskell
String to [Char] in haskell

Time:09-17

In Haskell, I got this string "bbbbffff", and I want to get a list in this form:

['b','b','b','b','f','f','f','f']

I think that I can use map, but sincerely, I don't know how to begin, and are a lot of things that I do not understand in Haskell.

Thanks in advance.

CodePudding user response:

By default, a String is already a [Char] (see specification):

A string is a list of characters:

type  String  =  [Char]

They simply don't print as ['b','b','b',...] because [Char] and String is the same type and therefore indistinguishable and must be shown the same way. Indeed, if you input your list you'll see it formatted as a string:

Prelude> 42
42
Prelude> [1,2,3]
[1,2,3]
Prelude> ['b','b','b','b','f','f','f','f']
"bbbbffff"

This means that you can immediately pass it to any list function, without having to do anything with it:

myLength :: [Char] -> Int
myLength (c:rest) = 1   myLength rest
myLength [] = 0

-- Prints 11
main = print (myLength "hello world")

There are other textual data types like Data.Text, but these are for more advanced use and must be explicitly enabled and used.

  • Related