5

I would like to know if there is a simple way to turn [5,2,10] into "52a". Where its not just to this case, I want to associate any number >9 with the corresponding letter.

Thanks in advance.

1
  • 6
    What happens for numbers greater than 36? Commented Dec 1, 2010 at 13:07

2 Answers 2

9

You want to do something to each element of a list in order to get a new list. In other words, you want to apply a function (that you will have to define yourself) to each element. This is what the map function from the Prelude is for.

To convert between integers and individual characters, you could use the chr and ord functions from the Data.Char module.

So,

map (\i -> if i < 10 then chr (i + ord '0') else chr (i - 10 + ord 'a'))

is a function of type [Int] -> String that does what you want (no error checking included, though).

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

1 Comment

At least on GHC, the chr function will throw an exception when its argument is outside the legal range for unicode Chars (0 .. 0x10FFFF). Things will look rather... creative... long before that.
7

Slower but more elegant:

f = map ((['0'..'9'] ++ ['a'..'z']) !!)

If your numbers are 0-15 use map intToDigit from Data.Char.

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.