[Haskell-cafe] Haskell-Newbie and Char-Function

Richard O'Keefe ok at cs.otago.ac.nz
Sun Dec 6 21:39:31 EST 2009

On Dec 6, 2009, at 4:42 AM, MeAdAstra wrote:
> I only started learning Haskell some days ago. Maybe one of you can  
> give me
> a hint on how to implement a function that needs a character in the  
> range
> (a,b,...z) and an integer number k and returns the k-next neighbor  
> of the
> character? For example, fct a 5 would result in output f.

I'm reading between the lines here.  I think you want

alphabetic_successor :: Int -> Char -> Char
    alphabetic_successor k c
    requires k >= 0 and c `elem` lower_case_letters
    ensures result `elem` lower_case_letters
    where lower_case_letters = "abcdefghijklmnopqrstuvwxyz"

What's not clear from your description is what's supposed to
happen if you ask for alphabetic_successor 5 'z'.  I'll
assume you want to think of the letters being in a circle.

It is possible to hack this using character->integer
and integer->character conversion, but I'm going to do it
another way that doesn't depend on the characters being
contiguous in the Unicode character set.  You could use the
code to find the successor in a sequence of consonants, for

A.  We want to find the position of c in lower_case_letters.
     The first thing to do is to read the documentation and see
     if there is a suitable function.  There's one in the List
     module: elemIndex :: Eq x => x -> [x] -> Maybe Int.
     This will work for any type x (including characters) that
     supports equality (==).  It takes an item, a list of items,
     and either returns Nothing (the item wasn't found) or
     (Just n) -- the item was found at position n, 0 offset.

B.  We add k to n and reduce it modulo the length of the list.

C.  Given our new position, we want to find the character at
     that position in the list.  The function for that is
     list !! index.

import List (elemIndex)

alphabetic_successor k c = lower_case_letters !! new_index
   where Just index = List.elemIndex c lower_case_letters
         new_index = (k + index) `mod` length lower_case_letters
         lower_case_letters = "abcdefghijklmnopqrstuvwxyz"

More information about the Haskell-Cafe mailing list