Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell get character array from string?

Tags:

haskell

Is it possible if given a string I could get each character composing that string?

like image 321
user997112 Avatar asked Nov 07 '11 20:11

user997112


2 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.

like image 171
fuz Avatar answered Nov 05 '22 18:11

fuz


Well, the question does say he wants an array:

import Data.Array
stringToArray :: String -> Array
stringToArray s = listArray (0, length s - 1) s
like image 24
alternative Avatar answered Nov 05 '22 19:11

alternative