Search code examples
haskelltoupper

Understanding Haskell's `toUpper`


Looking at the Haskell source for toUpper:

toUpper c = chr (fromIntegral (towupper (fromIntegral (ord c))))  
... 
foreign import ccall unsafe "u_towupper"
  towupper :: CInt -> CInt

What is the meaning of chr, as well as u_towupper? I'm curious about the foreign import ccall unsafe part too. Does the Haskell source actually mutate, hence the unsafe?


Solution

  • First ord converts a Char to an Int, then fromIntegral converts it to CInt. On the other side fromIntegral converts a CInt to an Int, then chr converts the Int to a Char.

    An unsafe foreign import means that the C function u_towupper does not call back into haskell. If Ghc knows this, then it can make some optimizations. It has nothing to do with mutation.