Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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?

like image 680
tom Avatar asked Mar 01 '20 10:03

tom


1 Answers

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.

like image 109
bradrn Avatar answered Oct 12 '22 22:10

bradrn