Purescript: convert Char to Lowercase version

Viewed 123

What is the better way to convert a given Char to lowercase version?

One method could be with converting to String:

charToLower :: Char -> Char
charToLower char =
   Maybe.fromMaybe char 
     $ CodeUnits.charAt 0 
     $ String.toLower 
     $ CodeUnits.singleton char

Is there a more appropriate way in terms of performance/simplicity?

There is also a toLower` from CodePoint.Unicode package but I wonder if it is a preferred way.

1 Answers

I guess the fastest way is just to use FFI. One can easily write toLower this way:

// Foreign/Char.js

module.exports.toLower = function charToLower(c) {
  return c.toLower();
}
-- Foreign/Char.purs
module Foreign.Char where

foreign import toLower :: Char -> Char

Or if you want to express it in purescript only:

import Unsafe.Coerce (unsafeCoerce)
import Data.String as S

toLower :: Char -> Char
toLower = unsafeCoerce >>> S.toLower >>> unsafeCoerce

That eventually boils down to the same js code. You cannot break Char's invariants as it's initially just a subset of String and has the same runtime representation.

Related