How to return the next letter in the alphabet of given letter wrapped around in Haskell [closed]

StackOverflow https://stackoverflow.com/questions/20746646

  •  21-09-2022
  •  | 
  •  

Question

I'm trying to implement a function that returns the next letter in alphabetical order. For example:

> returnNext 'A'
  'B'

But also:

> returnNext 'Z'
  'A'

The function should thus cycle between char codes in alphabetical order (mod 26).

Was it helpful?

Solution

Two ways come to mind

import Data.Char
returnNext c = chr (((1 + ord c - ord 'A') `mod` 26) + ord 'A')

Which is kind of ugly to say the least.

And:

returnNext 'Z' = 'A'
returnNext c = chr (ord c + 1)

Both behave differently when not given a letter of the alphabet, but since you didn't specify what should happen in this case I'll assume it's OK.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top