How to "subtract" one character from another?

Viewed 100

Is it possible to subtract two Char values? For example

'B' - 'A' = 1, 
'C' - 'A' = 2

Can some functions handle this?

1 Answers

There's no universally defined notion of what difference between characters is (for instance, is K more similar to k than l is, or less?) so the safest thing might be to define the function yourself based on the requirements. You can guard-match on character ranges:

import Data.Char

charDist c d
 | isLower c, isLower d  = ...
 | isLower c, isUpper d  = ...
 | ...

Within each range, you can probably just use Unicode as the proxy space. The Enum class maps char values to ints, which can be subtracted in the obvious way:

charDist c d
 | isLower c, isLower d  = fromEnum c - fromEnum d
 | ...
Related