Is it possible if given a string I could get each character composing that string?
3 Answers
In Haskell, strings are just (linked) lists of characters; you can find the line
type String = [Char]
somewhere in the source of every Haskell implementation. That makes tasks such as finding the first occurence of a certain character (elemIndex 'a' mystring) or calculating the frequency of each character (map (head &&& length) . group . sort) trivial.
Because of this, you can use the usual syntax for lists with strings, too. Actually, "foo" is just sugar for ['f','o','o'], which in turn is just sugar for 'f' : 'o' : 'o' : []. You can pattern match, map and fold on them as you like. For instance, if you want to get the element at position n of mystring, you could use mystring !! n, provided that 0 <= n < length mystring.
5 Comments
map sum . group . sort is ill-typed for strings. Perhaps you meant something like map (head &&& length) . group . sort?"abc" or of type String or equally [Char] is a String as described above.newtype String2 = String2 String, but not exporting the constructor, I thinkWell, the question does say he wants an array:
import Data.Array
stringToArray :: String -> Array
stringToArray s = listArray (0, length s - 1) s
1 Comment
The string type is just an alias for [Char] so you don't need to do anything.
Prelude> tail "Hello"
"ello"
Prelude> ['H', 'e', 'l', 'l', 'o']
"Hello"
Prelude> "Hello" !! 4
'o'
id.