Shifting elements in a string

Viewed 75

I'm pretty new to haskell and I wanted to make a function to take a string and add a certain number to shift the elements of the string.

e.g

addChars "abcd" 2
output -> "cdef"

I was able to do it but with just a single character using:

nextChar :: Char -> Int -> Char
nextChar x y= chr $ ord x + y
1 Answers

You can work with map, here you will need to call nextChar with a value for the second parameter

addChars :: String -> Int -> String
addChars cs dc = map (`nextChar` dc) cs

Often in Haskell the parameters will be reversed, so we define a function:

nextChar :: Int -> Char -> Char
nextChar dc c = chr (ord c + dc)

and then we can define addChars as:

addChars :: Int -> String -> String
addChars dc cs = map (nextChar dc) cs

or shorter:

addChars :: Int -> String -> String
addChars = map . nextChar
Related