14

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

3
  • Yes. I think that strings are list of char in Haskell. Commented Nov 7, 2011 at 20:27
  • 1
    What do you want to do with the characters? Commented Nov 7, 2011 at 22:40
  • Yes, the function is called id. Commented Nov 9, 2011 at 6:15

3 Answers 3

18

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.

Sign up to request clarification or add additional context in comments.

5 Comments

map sum . group . sort is ill-typed for strings. Perhaps you meant something like map (head &&& length) . group . sort?
So say I passed a string in as a parameter to a function, how would I actually access each char? using map?
@FUZxxl, what happens if you're using an abstract data type, which is not technically a string, but is a string..... how do you get the characters then?
@user997112 I don't understand your question. Except some esoteric extensions to Haskell, anything declared as "abc" or of type String or equally [Char] is a String as described above.
@FUXxxl he means newtype String2 = String2 String, but not exporting the constructor, I think
15

Well, the question does say he wants an array:

import Data.Array
stringToArray :: String -> Array
stringToArray s = listArray (0, length s - 1) s

1 Comment

This is what I came looking for. In fact, this is the correct answer to the question, even if it wasn't what the OP intended.
7

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.