3

I'm trying to find a function that converts a Char to a Word8, and another that converts it back. I've looked on Hoogle and there are no functions of type Char -> Word8. I want to do this because Word8 has an instance of the Num class, and I would be able to add numbers to them to change them to another number. For example, my function would look something like:

shift :: Char -> Int -> Char
shift c x = toChar $ (toWord8 c) + x

Any ideas?

user3791260
  • 65
  • 1
  • 3

2 Answers2

6

You can use fromEnum and toEnum to go via Int instead. This has the added benefit of also supporting Unicode.

> toEnum (fromEnum 'a' + 3) :: Char
'd'
hammar
  • 138,522
  • 17
  • 304
  • 385
2

I found these using FP Complete's Hoogle: http://haddocks.fpcomplete.com/fp/7.7/20131212-1/utf8-string/Codec-Binary-UTF8-String.html#v:encodeChar

A Char doesn't necessarily contain only one byte, so the conversions you're describing could lose information. Would these functions work instead?

David Young
  • 10,713
  • 2
  • 33
  • 47