4

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).

SND
  • 1,552
  • 2
  • 16
  • 29
user3094936
  • 263
  • 6
  • 12
  • 2
    Start with http://stackoverflow.com/questions/3261236/how-to-get-ascii-value-of-character-in-haskell , then figure out how to increment a *number* with a wraparound. – Anton Kovalenko Dec 23 '13 at 15:43
  • What have you tried? You already seem to know what to do, but I don't see any code. – bheklilr Dec 23 '13 at 15:45

1 Answers1

12

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.

Guido
  • 2,571
  • 25
  • 37