Haskell: Function that converts Char to Word8 - haskell

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?

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'

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?

Related

How can I transform Char to Int in Haskell using "ord" function?

I have been trying to figure out how can I covert a Char to an Int in Haskell using the "ord" function from the Data.Char library. Here is where I got to now:
charToNum :: Char -> Int
charToNum x = (ord(x))
It is a pretty simple program, but I'm not a 100% sure how to work with an "ord" function
When I run compile the program, everything compiles, but when I try to enter a character I get this error:
> charToNum e
<interactive>:85:11: error: Variable not in scope: e :: Char
e is not a character. I mean, it is of course a character of the string you typed into the prompt, like c and N are characters of that string, but as far as the parser is concerned all of these represent just parts of variable names. And, well, as GHCi then tells you that there is no variable named e.
If you want to pass the character ‘e’ as an argument then do just that!
> charToNum 'e'
charToNum 'e'?
BTW, your definition should read
charToNum x = ord x
(Or simply
charToNum = ord
)

What is the purpose of the function (toEnum . fromEnum) in Haskell code?

I saw the function toEnum . fromEnum being used on Chars in HaskellNet.Network.Auth.
b64Encode :: String -> String
b64Encode = map (toEnum.fromEnum) . B64.encode . map (toEnum.fromEnum)
b64Decode :: String -> String
b64Decode = map (toEnum.fromEnum) . B64.decode . map (toEnum.fromEnum)
At first glance this function should be identical to id, right? Why is it here?
It can be equivalent to id, but only in certain situations. Since fromEnum :: Enum a => a -> Int can convert any Enum to an Int, and toEnum :: Enum a => Int -> a can convert an Int to any Enum, it follows that toEnum . fromEnum is a general method of converting from any enum to any enum — that is, (toEnum . fromEnum) :: (Enum a, Enum b) => a -> b. As you have observed, this should indeed identical to id (if the Enum instance has been implemented properly, that is), but only when you select a and b as being the same type; otherwise, it converts from one Enum instance to a different Enum instance.
As for why it is used in that particular place: I really have no idea. B64.decode and B64.encode appear to both be String -> String, and b64Decode and b64Encode are also String -> String, so toEnum . fromEnum converts from Char to Char — so in this case it should be identical to id. In other words, toEnum . fromEnum does nothing here and probably should be removed (although I won’t rule out the possibility that the Enum instance for Char is implemented in such a way that this isn’t id).
EDIT: #K.A.Buhr has found an explanation for this in the Git history of the project. It appears that encode and decode used to have signatures involving ByteString, so toEnum and fromEnum were used to convert between lists of Word8 (for ByteString) and lists of Char (for String). At some point encode and decode were switched to use String rather than ByteString, but no-one removed the toEnum and fromEnum.

How to generate strings drawn from every possible character?

At the moment I'm generating strings like this:
arbStr :: Gen String
arbStr = listOf $ elements (alpha ++ digits)
where alpha = ['a'..'z']
digits = ['0'..'9']
But obviously this only generates strings from alpha num chars. How can I do it to generate from all possible chars?
Char is a instance of both the Enum and Bounded typeclass, you can make use of the arbitraryBoundedEnum :: (Bounded a, Enum a) => Gen a function:
import Test.QuickCheck(Gen, arbitraryBoundedEnum, listOf)
arbStr :: Gen String
arbStr = listOf arbitraryBoundedEnum
For example:
Prelude Test.QuickCheck> sample arbStr
""
""
"\821749"
"\433465\930384\375110\256215\894544"
"\431263\866378\313505\1069229\238290\882442"
""
"\126116\518750\861881\340014\42369\89768\1017349\590547\331782\974313\582098"
"\426281"
"\799929\592960\724287\1032975\364929\721969\560296\994687\762805\1070924\537634\492995\1079045\1079821"
"\496024\32639\969438\322614\332989\512797\447233\655608\278184\590725\102710\925060\74864\854859\312624\1087010\12444\251595"
"\682370\1089979\391815"
Or you can make use of the arbitrary in the Arbitrary Char typeclass:
import Test.QuickCheck(Gen, arbitrary, listOf)
arbStr :: Gen String
arbStr = listOf arbitrary
Note that the arbitrary for Char is implemented such that ASCII characters are (three times) more common than non-ASCII characters, so the "distribution" is different.
Since Char is an instance of Bounded as well as Enum (confirm this by asking GHCI for :i Char), you can simply write
[minBound..maxBound] :: [Char]
to get a list of all legal characters. Obviously this will not lead to efficient random access, though! So you could instead convert the bounds to Int with Data.Char.ord :: Char -> Int, and use QuickCheck's feature to select from a range of integers, then map back to a character with Data.Chra.chr :: Int -> Char.
When we do like
λ> length ([minBound..maxBound] :: [Char])
1114112
we get the number of all characters and say Wow..! If you think the list is too big then you may always do like drop x . take y to limit the range.
Accordingly, if you need n many random characters just shuffle :: [a] -> IO [a] the list and do a take n from that shuffled list.
Edit:
Well of course... since shuffling could be expensive, it's best if we chose a clever strategy. It would be ideal to randomly limit the all characters list. So just
make a limits = liftM sort . mapM randomRIO $ replicate 2 (0,1114112) :: (Ord a, Random a, Num a) => IO [a]
limits >>= \[min,max] -> return . drop min . take max $ ([minBound..maxBound] :: [Char])
Finally just take n many like random Chars like liftM . take n from the result of Item 2.

Haskell int to float and char to float

Is there a function in haskell which converts from int to float, and from char to float?
I know that there is a function that converts from char to int and int to char.
fromIntegral will convert from Int to Float.
For Char to Float, it depends. If you want to get the ASCII value of a Char (ignoring Unicode for now), use Data.Char.ord:
Prelude Data.Char> fromIntegral (ord '2') :: Float
50.0
If you want to read the digit of a Char, i.e. '2' becomes the value 2, you can do this:
char2float :: Char -> Float
char2float n = fromInteger (read [n])
Prelude Data.Char> char2float '2'
2.0
If you're going to do a lot of this, you might consider using an actual parsing library to get actual error handling.
Questions like this can be answered with hoogle.
For example, Hoogle for "Char -> Int" and the first function listed will do it (ord, mentioned in other answers, is the second result):
digitToInt :: Char -> Int
Though your need for a function :: Char -> Float does mandate using read (third result down) or a combination of digitToInt and a function :: Int -> Float:
digitToFloat = toEnum . digitToInt
did you try:
intToFloat :: Int -> Float
intToFloat n = fromInteger (toInteger n)
Additionally see here
If I get it right, you can use Read typeclass for these purposes. And it means you can convert some basic types to some other basic types.
Converting from Int to a Float:
Prelude> 1::Float
1.0
BUT I don't know which means converting from char to Float - maybe [Char] to Float or String to Float? Anyway:
Prelude> read("1")::Float
1.0
Check out this link: http://book.realworldhaskell.org/read/using-typeclasses.html

What's the right way to divide two Int values to obtain a Float?

I'd like to divide two Int values in Haskell and obtain the result as a Float. I tried doing it like this:
foo :: Int -> Int -> Float
foo a b = fromRational $ a % b
but GHC (version 6.12.1) tells me "Couldn't match expected type 'Integer' against inferred type 'Int'" regarding the a in the expression.
I understand why: the fromRational call requires (%) to produce a Ratio Integer, so the operands need to be of type Integer rather than Int. But the values I'm dividing are nowhere near the Int range limit, so using an arbitrary-precision bignum type seems like overkill.
What's the right way to do this? Should I just call toInteger on my operands, or is there a better approach (maybe one not involving (%) and ratios) that I don't know about?
You have to convert the operands to floats first and then divide, otherwise you'll perform an integer division (no decimal places).
Laconic solution (requires Data.Function)
foo = (/) `on` fromIntegral
which is short for
foo a b = (fromIntegral a) / (fromIntegral b)
with
foo :: Int -> Int -> Float

Resources